Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a short date to a long date in Javascript?

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.

like image 855
James Anderson Avatar asked Mar 24 '23 22:03

James Anderson


1 Answers

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
like image 197
Bergi Avatar answered Apr 10 '23 08:04

Bergi