DomeTune DomeTune -4 years ago 154
Javascript Question

Why does same date has different hours?

Maybe the question is absolut obvious, but i dont get it. Why are the Dates in the Code Snippet different. Does the format say something about the hours as well?

console.log("2017-1-9 -->")
console.log(new Date("2017-1-9"))
console.log("2017-1-09 -->")
console.log(new Date("2017-1-09"))
console.log("2017-01-9 -->")
console.log(new Date("2017-01-9"))
console.log("2017-01-09 -->")
console.log(new Date("2017-01-09"))
console.log("2017-01-11 -->")
console.log(new Date("2017-01-11"))

.as-console-wrapper {
min-height: 100%;

Even in my chrome-console and the code-snippet-console i get different dates.
enter image description here

My problem is not that both consoles log different dates. Look only at the
in each console, for the very same date, only the
is different.
Consequently my question:

Why are the dates different?

## UPDATE ##

Why is
new Date("2017-1-1").getTime() != new Date("2017-01-01").getTime() --> true

var date = new Date("2017-2-9");
var dateWithZero = new Date("2017-02-09");
console.log(date.getTime() == dateWithZero.getTime());

.as-console-wrapper {
min-height: 100%;

Answer Source

TL;DR: Because the language specification says that date strings not conforming to the specified format can be parsed according to "any implementation-specific heuristics or implementation-specific date formats," and YYYY-M-D is just such a string.

Let's dive into the spec. Here's what the ECMAScript 5.1 spec says about the Date constructor (I'm quoting it instead of the current, ES2016 spec just because it's simpler, but the latter works basically the same in this case): new Date (value)


The [[PrimitiveValue]] internal property of the newly constructed object is set as follows:

  1. Let v be ToPrimitive(value).
  2. If Type(v) is String, then

    • Parse v as a date, in exactly the same manner as for the parse method (; let V be the time value for this date.
  3. ...

And here's the spec for parse (emphasis mine): Date.parse (string)

The parse function applies the ToString operator to its argument and interprets the resulting String as a date and time... The function first attempts to parse the format of the String according to the rules called out in Date Time String Format ( If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. ...

Date Time String Format, in a nutshell, is YYYY-MM-DDTHH:mm:ss.sssZ and its subsets. Since YYYY-M-D doesn't conform to that format, the interpreter is (unfortunately) free to do whatever it wants. If you want to know why Chrome does it in this particular way, you'll have to dig around in the V8 source.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download