简体   繁体   中英

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.

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

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

You can use:

new Date(2013, 06, 04)

...or directly using a date string (ie 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 .

您必须将13设置为2013,否则将默认使用1913

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM