简体   繁体   中英

converting a date string to ISO 8601 format string and eventually a date object

i'll make it simple ... getting from a post request a Date string as:

var str = "25/01/2014";

however, when using the Date.parse() function like this:

var date = Date.parse (str);

i am getting a NaN when i'm trying to print it.

what is the recommended way to format such string to a iso-8601 format, or any other way i can convert such string into a Date format?

See Converting string to date in js for general advice regarding date string format conversion.

Applied to your specific case:

 // Convert DD/MM/YYYY to ISO format YYYY-MM-DD: let string = "01/02/2016"; let re = /(\\d+)\\/(\\d+)\\/(\\d+)/; let date = new Date(string.replace(re, "$3-$2-$1")); console.log(date); 

To say truth your code works in my system. But if you want to be on safe side then split the string and create date object from it.

var a = '25/01/2014';
var b = a.split('/');
var d = new Date(b[2],b[1],b[0]);

If you know that the supplied string str has dd/mm/yyyy format then you can just use

var date= new Date( str.split( "/" ).reverse() );

Date.parse is guaranteed to parse a simplified ISO-8601 format. Whether other formats will be recognized is up to the implementation. But note that the code above passes year, month and day as numbers to the constructor, so it hasn't to parse it again.

Edit:

My code above is wrong . It just works for me because the reversed array will be converted to the string "2014,01,25", which Mozilla's Date.parse happens to accept. You need to pass the arguments separately as @Alex Kudryashev and @le_m have suggested. Even

Date.prototype.constructor.apply( null, array )

won`t work, because the Date constructor behaves differently when invoked as a function.

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