Reputation: 566
I need to convert 04/06/13 (for example) to a long date - Tue Jun 04 2013 00:00:00 GMT+0100 (BST). How can I do this using Javascript? I know how to convert a long date to a short date - just not the other way round.
Upvotes: 4
Views: 10226
Reputation: 664375
You could try the parsing functionality of the Date
constructor, whose result you then can stringify:
> new Date("04/06/13").toString()
"Sun Apr 06 1913 00:00:00 GMT+0200" // or something
But the parsing is implementation-dependent, and there won't be many engines that interpret your odd DD/MM/YY
format correctly. If you had used MM/DD/YYYY
, it probably would be recognized everywhere.
Instead, you want to ensure how it is parsed, so have to do it yourself and feed the single parts into the constructor:
var parts = "04/06/13".split("/"),
date = new Date(+parts[2]+2000, parts[1]-1, +parts[0]);
console.log(date.toString()); // Tue Jun 04 2013 00:00:00 GMT+0200
Upvotes: 4
Reputation: 23472
An alternative to the split method, uses lastIndexof and slice instead, to change the year to ISO8601 format which then gives a non-standard string that is known to be working across browsers, and then uses the date parsing method. (assuming a fixed pattern like in question)
However,
If you want to ensure how it is parsed, you have to do it yourself and feed the single parts into the constructor:
, this would mean using the split method, see @Bergi answer.
var string = "04/06/13",
index = string.lastIndexOf("/") + 1,
date = new Date(string.slice(0, index) + (2000 + parseInt(string.slice(index), 10)));
console.log(date);
Output
Sat Apr 06 2013 00:00:00 GMT+0200 (CEST)
On jsfiddle
or a further alternative would be to use moments.js
var string = "04/06/13";
console.log(moment(string, "DD/MM/YY").toString());
Output
Sat Apr 06 2013 00:00:00 GMT+0200 (CEST)
On jsfiddle
Upvotes: 2
Reputation: 471
You can use:
new Date(2013, 06, 04)
...or directly using a date string (i.e. a string representing a date as accepted by the parse method):
new Date("2013/06/04");
...or by specifying the different parts of your date, like:
new Date(year, month, day [, hour, minute, second, millisecond]);
Take a look at this.
Upvotes: 1
Reputation: 505
You have to take 13 as 2013 otherwise it will take default 1913
alert(new Date('04/06/2013'));
Upvotes: 0