简体   繁体   中英

Javascript Date object different depending on format: yyyy-mm-dd vs mm-dd-yyyy

Another JavaScript Date conundrum...

I get two completely different Date objects depending on the format I pass to the Date constructor (Date.parse() also produces different results).

=> Wed Apr 27 2016 00:00:00 GMT-0500 (Central Daylight Time)

=> 1461733200000

vs

Apr 26 2016 19:00:00 GMT-0500 (Central Daylight Time)

=> 1461715200000

I can easily work around this situation in my code, but I would like an explanation as to why/how this is doing what it does.

The ISO format you use in the second example has UTC as its default timezone. It's described here on MDN . If you want the correct behaviour for this format, you have to add the information about timezone: new Date('2016-04-27 GMT-0500'); or you have to also specify the time: new Date('2016-04-27 00:00:00');

In my opinion it's better not to use the built-in parser and use some library instead. For example Moment.js is great.

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