How to convert short date to 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 with Javascript? I know how to convert a long date to a short date - just not the other way around.

+4
source share
4 answers

You can try the parser functions of the Date constructor , the result of which you 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 correctly interpret your odd DD/MM/YY format. If you used MM/DD/YYYY , this would probably be universally recognized.

Instead, you want to make sure how it is parsed, so you need to do it yourself and pass the individual parts to 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 
+3
source

You can use:

 new Date(2013, 06, 04) 

... or directly using a date string (for example, a string representing the date accepted by the parse method):

 new Date("2013/06/04"); 

... or by specifying different parts of your date, for example:

 new Date(year, month, day [, hour, minute, second, millisecond]); 

Take a look at this .

+1
source

An alternative to the split method is to use lastIndexof and slice instead to change the year to the ISO8601 format, which then yields a non-standard string that is known to work in all browsers and then uses the date analysis method . (assuming a fixed pattern, as in the question)

but

If you want to make sure how it is disassembled, you must do it yourself and feed the individual parts to the constructor:

this will 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) 

Jsfiddle on

or another 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) 

Jsfiddle on

+1
source

You must accept 13 in 2013, otherwise it will default to 1913

 alert(new Date('04/06/2013')); 
0
source

Source: https://habr.com/ru/post/1481543/


All Articles