简体   繁体   中英

How to parse yyyy-MM-dd HH:mm:ss.SSS format date in javascript?

 const time = '2016-11-16 00:00:00.000'; const date = new Date(time); console.info(date);

It seems safari cannot parse yyyy-MM-dd HH:mm:ss.SSS format date( it returns NaN ) while chrome works fine, how can I parse this?

try using moment js for that. look at: moment.js parse with format for example:

var mydate = moment("2016-11-16 00:00:00.000", "yyyy-MM-dd HH:mm:ss.SSS").toDate();

didn't test the format I put there as moment.js might use different strings to define it but you can see it all in the doc link I wrote above

I'd use momentjs for working with dates in javascript. Easy example:

 var time = '2016-11-16 00:00:00.000'; var m = moment.utc(time, "YYYY-MM-DD HH:mm:ss.SSS"); console.log(m)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment-with-locales.min.js"></script>

 const time = '2016-11-16 00:00:00.000'; const date = new Date(time); console.info(date);

It seems safari cannot parse yyyy-MM-dd HH:mm:ss.SSS format date( it returns NaN ) while chrome works fine, how can I parse this?

If Safari is been picky about the DataTime format, you could maybe do some simple string replace & concatenation.

 const time = '2016-11-16 00:00:00.000'; const date = new Date(time.replace(' ','T') + 'Z'); console.info(date);

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