3

Oh Javascript... ?

 5 years ago
source link: https://www.tuicool.com/articles/hit/b6jeMnn
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Just ran across this little gem.

new Date('2018-01-01')
<- Sun Dec 31 2017 18:00:00 GMT-0600 (Central Standard Time)

new Date('2018/01/01')
<- Mon Jan 01 2018 00:00:00 GMT-0600 (Central Standard Time)

The reason this happens (I think) is because JS parses the first date as ISO 8601 format. And since no timezone offset is specified it assumes UTC. However, JavaScript will only create Dates in local time. So after applying the local time zone, it is 6pm the previous day.

The second one uses a / separator, so it does not trigger the ISO parse branch. Instead it sensibly presumes I am interested in a date in the current time zone.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK