Friday, March 25, 2022

JavaScript Date object is actually worse than I thought

So a few years ago I was complaining about some weird behavior I discovered in the JavaScript Date object. In particular, that new Javascript('2018-01-01') creates an object at GMT/UTC 0. Which is fine, except that the .getFullYear() method gets a value localized to my current time zone, which leads to unexpected results when my date is different than GMT-0.

I was just playing around with this again, and discovered that whether Date creates a localized object or not depends on the format of the value passed to the constructor:

new Date('2018-01-01')
Date Sun Dec 31 2017 17:00:00 GMT-0700 (Mountain Standard Time)
new Date('January 1, 2018')
Date Mon Jan 01 2018 00:00:00 GMT-0700 (Mountain Standard Time)

So yeah, kinda awful.

No comments:

Post a Comment