Exploring the difference between using new Date("2017-01-01") and new Date("2017-1-1")
The syntax new Date("2017-01-01")
strictly adheres to the specifications (details below). On the other hand, when you use
new Date("2017-1-1")
, it diverges from the standard and relies on any
"...implementation-specific heuristics or implementation-specific date formats" that are applied by the JavaScript engine. Consequently, there is uncertainty in how or if the input will be parsed successfully, and if so, whether it will be interpreted as UTC time or local time.
Despite being compliant with the specifications, new Date("2017-01-01")
has faced inconsistencies across different browser implementations over time due to its lack of timezone indicator:
- In ES5 reference (December 2009), strings lacking a timezone indicator were supposed to be parsed in UTC. This conflicted with the ISO-8601 standard, stating that such strings should be considered local time, not UTC. Hence, in ES5,
new Date("2017-01-01")
was parsed in UTC.
- ES2015 (also known as ES6, June 2015) specified that strings without a timezone indicator should be treated as local time similar to ISO-8601. Consequently, in ES2015,
new Date("2017-01-01")
was interpreted as local time.
- However, this was revised in ES2016 (June 2016) following years of browsers parsing date-only forms with "-" as UTC. Therefore, starting from ES2016, only "date-only" forms like
"2017-01-01"
are parsed in UTC, while "date/time" forms like "2017-01-01T00:00:00"
are processed in local time.
Regrettably, not all JavaScript engines conform precisely to the specifications. For instance, Chrome (version 56 at the time of writing) incorrectly interprets date/time forms as UTC instead of local time (similarly to IE9). Conversely, Chrome, Firefox, and IE11 handle date-only forms correctly by considering them as UTC. Meanwhile, IE8 does not support the ISO-8601 format since it predates the release of the ES5 spec.