Date.parse (0) returns midnight 2000, why?

When I try Date.parse() an integer or string 0 , it returns 946681200000, which corresponds to the date:

Sat 01.01.2000 00:00:00 GMT + 0100 (CET)

Why?

I would suggest that the parser interprets a single zero in 2000, but the specifications say nothing about the one-character definition of a year β€” RFC 2822 and ISO 8601 require a four-digit year in a row.

I would like to better understand how the string '0' is parsed in Date, why it is accepted as a valid date (if it will not be NaN or some such?) And why 2000 is chosen instead, for example, 1900.

Update

After some trial and error, I found that one number is actually interpreted differently in different numerical ranges.

  • 0 - 12: month of 2000
  • 13 - 31: NaN
  • 32 - 49: year + 2000, with all other values, the default values ​​are set
  • 50 - 99: year + 1950, with all other values, the default values ​​are set
  • 100 - ??: year, with all other default values
+6
source share
2 answers

the specifications say nothing about the definition of a single year symbol

The specification says:

If String does not match this format , the function can return to any implementation-specific heuristics, or to implementation date formats.

For V8 in particular, see this error report for unpredictable results when calling with the same number. You can also read the source directly ( dateparser.cc , dateparser.h , dateparser-inl.h ).

+8
source

As Bergi correctly points out, the specification leaves it until implementation to return a date when it is not one of the standard formats.

Here's how it is implemented in the Chromium V8 processor:

Dateparser.cc

 if (!is_iso_date_) { if (Between(year, 0, 49)) year += 2000; else if (Between(year, 50, 99)) year += 1900; } 

In Chrome 41.0.2272.76 :

Date.parse(0) returns 946665000000 , which is Sat Jan 01 2000 00:00:00

Date.parse(49) returns 2493052200000 , which is Fri Jan 01 2049 00:00:00

Date.parse(50) returns -631171800000 , which is equal to Sun Jan 01 1950 00:00:00

(Translated time is GMT+5.30 ; the millisecond value will change depending on your time zone)

Firefox returns NaN for all of these cases.

0
source

Source: https://habr.com/ru/post/983860/


All Articles