简体   繁体   中英

Best way to create a Date Object with this string in JS

I'm receiving this date/time from an API:

2012-03-31 12:00:00

What is the best way to do this:

var date = new Date("2012-03-31 12:00:00") without Firefox complaining of an Invalid Date?

You can match all the fields in the date time string with:

var str = "2012-03-31 12:00:00";
var fields = str.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);

Now fields[1] contains the year, fields[2] the month, etc. Then you can call Date with:

// months are zero-based, so we have to subtract 1
var date = new Date(+fields[1], +fields[2] - 1, +fields[3], +fields[4], +fields[5], +fields[6]);

Or use a library like http://momentjs.com/ which does this for you.

If you just want the date you could use:

var date = new Date("2012-03-31 12:00:00".split(" ")[0]);

& firefox wont complain.

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