I need a js Date object with specified values for date and year. I would expect
new Date("2000-01-01")
to give me Date object with 2000 as value for getFullYear()
, but if my computer's time settings are set to Chicago timezone, I'm getting Fri Dec 31 1999 18:00:00 GMT-0600 (CST)
, and for Buenos Aires: Fri Dec 31 1999 22:00:00 GMT-0200 (ARST)
.
Is there a way to create Date object, with .getFullYear()
returning the date we set in constructor, no matter what timezone is set on user's machine?
Update:
I need this Date object to be used in another library (which calls its .getFullYear()
method, so using UTC getters doesn't really help.
You can write new method to 'Date.prototype', and use it to get date which will be including the local timezone offset.
When parsing a string to a
Date
in JavaScript, a value that is inYYYY-MM-DD
format is interpreted as a UTC value, rather than a local-time value.The key is that the parts are separated by hyphens, and that there is no time zone information in the string. The ECMAScript 5.1 Spec says in §15.9.1.15:
That means, if you don't specify an offset, it will assume you meant UTC.
Note that since this is the opposite of what ISO-8601 says, this is behavior has been changed in ECMAScript 2015 (6.0), which says in §20.3.1.16:
Therefore, when this provision of ES6 is implemented properly, string values of this format that used to be interpreted as UTC will be interpreted as local time instead. I've blogged about this here.
The workaround is simple. Replace the hyphens with slashes:
Another workaround that is acceptable is to assign a time of noon instead of midnight to the date. This will be parsed as local time, and is far enough away to avoid any DST conflicts.
Alternatively, consider a library like moment.js which is much more sensible.