7

Hi I have a string 'Windows-10' which when I try to parse via new Date() constructor it is getting parsed and gives a completely valid date as 'Mon Oct 01 2001 00:00:00 GMT+0530 (India Standard Time)'

I dont know why is this happening I also tried it with other Windows string such as 'Windows-7', 'Windows-99' etc. and they all parse easily.

Vibhanshu Biswas
  • 379
  • 1
  • 15
  • Doesn’t happen in Firefox 65.0a1. I get `Invalid Date`. – Sebastian Simon Nov 02 '18 at 10:57
  • What is your computer date? – asdf_enel_hak Nov 02 '18 at 10:58
  • Is this just because you're interested, or does it cause trouble? – d0n.key Nov 02 '18 at 11:02
  • Which browser or environment are you using? – Sebastian Simon Nov 02 '18 at 11:03
  • @Xufox Works in Chrome 70 – barbsan Nov 02 '18 at 11:08
  • Node 11.0.0 outputs `2001-09-30T22:00:00.000Z`, `2001-06-30T22:00:00.000Z`, `1998-12-31T23:00:00.000Z`, respectively. Apparently, `99` is parsed as the year 1999, `10` and `7` as the months October and July, respectively. – Sebastian Simon Nov 02 '18 at 11:08
  • `new Date('whatever-27')` results in Invalid Date but `'whatever-37'` and `'whatever-127'` are parsed – barbsan Nov 02 '18 at 11:15
  • 1
    [`new Date(dateString)` uses `Date.parse(dateString)`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax). Docs say that ["results may be unexpected"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Parameters). – Michael H. Nov 02 '18 at 11:25
  • 4
    Possible duplicate of [is there any workaround for broken v8 date parser?](https://stackoverflow.com/questions/30964943/is-there-any-workaround-for-broken-v8-date-parser) – barbsan Nov 02 '18 at 11:31

1 Answers1

1

The behavior you witnessed is implementation-specific, which for the one-arg Date(value) constructor is covered by the ECMA-262 spec in chapter 20.3.2.2. Your example will walk through to step 3.b.ii.1. which states that the string will be parsed according to the rules laid out in chapter 20.3.3.2 for the Date.parse(string) method. That method specification defines:

The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. Unrecognizable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN.

Because your strings obviously do not comply with the Date Time String Format the browser falls back to its implementation-specific algorithm. My Chrome 70, e.g., returns a Date object for the current time which corresponds to calling the no-args Date() constructor. IE11 on the other hand parses the string to NaN and returns a Date object with an "invalid date" value.

altocumulus
  • 21,179
  • 13
  • 61
  • 84