Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

v8

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

Sat Jan 01 2000 00:00:00 GMT+0100 (CET)

Why?

I would assume that the parser interprets the single zero as a year 2000, but the specs say nothing about single-character year definition - both RFC 2822 and ISO 8601 require a four-character year in the string.

I would like to better understand how the string '0' is parsed into a Date, why is it accepted as a valid Date (should it not be NaN or some such?) and why the year 2000 is chosen instead of for example 1900.

Update

After some trial & error, I discovered that the single number is in fact interpreted differently in different numeric ranges.

  • 0 - 12: A month of year 2000
  • 13 - 31: NaN
  • 32 - 49: A year + 2000, with all the other values set to defaults
  • 50 - 99: A year + 1950, with all the other values set to defaults
  • 100 - ??: A year, with all the other values set to defaults
like image 458
Robert Rossmann Avatar asked Mar 16 '15 10:03

Robert Rossmann


People also ask

What does date parse mean?

parse() The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

How do you parse a date?

parse() parses a date string and returns the time difference since January 1, 1970. parse() returns the time difference in milliseconds.


1 Answers

the specs say nothing about single-character year definition

The spec says:

If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

For V8 specifically, see this bug report on unpredictable results when called with a single number. You can also read the source directly (dateparser.cc, dateparser.h, dateparser-inl.h).

like image 151
Bergi Avatar answered Sep 20 '22 01:09

Bergi