javascript Date timezone issue

When parsing a string to a Date in JavaScript, a value that is in YYYY-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:

… The value of an absent time zone offset is “Z”.

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:

… If the time zone offset is absent, the date-time is interpreted as a local time.

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:

var s = "2000-01-01";
var dt = new Date(s.replace(/-/g, "https://stackoverflow.com/"));

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.

var s = "2000-01-01";
var dt = new Date(s + "T12:00:00");

Alternatively, consider a library like moment.js which is much more sensible.

var s = "2000-01-01";
var dt = moment(s, 'YYYY-MM-DD').toDate();

Leave a Comment