What is the better way to split Date string in JavaScript?
44,322
Solution 1
should do the same
var newDate = '2015-04-10'.split('-').reverse().join('.')
// ^ ^ ^ join to 10.04.2015
// | |reverses (2 -> 0, 1 -> 1, 0 -> 2)
// | delivers Array
Solution 2
You could use a regular expression that has capture groups and use String.prototype.replace
to reformat it.
var newDate = myString.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3.$2.$1');
Solution 3
Yes.
var newDate = '2015-04-10'.split('-').reverse().join('.');
Author by
DaniKR
Updated on August 04, 2020Comments
-
DaniKR almost 4 years
I am getting from api xml data, where one of the xml elements is date time, which nodeValue is always in this format - string: "YYYY-MM-DD". (I can not request from api, to return me date time in diffrent format)
My problem is to split and convert this format into this string: "DD.MM.YYYY"
Basicly I did this:
var myString = "2015-04-10"; //xml nodeValue from time element var array = new Array(); //split string and store it into array array = myString.split('-'); //from array concatenate into new date string format: "DD.MM.YYYY" var newDate = (array[2] + "." + array[1] + "." + array[0]); console.log(newDate);
Here is jsfiddle: http://jsfiddle.net/wyxvbywf/
Now, this code works, but my question is: Is there a way to get same result in fewer steps?
-
Andreas Louv about 9 yearsFunky comment style o.o
-
DaniKR about 9 yearsyou are the best, tnx for suggestion and explanation, it works great :) upvote + accept (i need to wait for accept 5 min)
-
KooiInc about 9 years@krnekires glad I coul help ;)
-
Mahi about 4 yearsI need to do the opposite but this one line solution is just mind blowing lol, came as a surprise to me. Thx a lot