Why does the same date have different hours?

前端 未结 3 1979
余生分开走
余生分开走 2021-01-22 20:16

Maybe the answer is obvious, but I don\'t get it. Why are the Dates in the Code Snippet different? Does the format say something about the hours as well?

3条回答
  •  Happy的楠姐
    2021-01-22 20:34

    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):

    15.9.3.2 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 (15.9.4.2); let V be the time value for this date.
    3. ...

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

    15.9.4.2 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 (15.9.1.15). 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.

提交回复
热议问题