0

Why does new Date("best-of-5") parse as 2001-04-30T22:00:00.000Z in Chrome and Node?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    [_"...the value produced by this function is implementation-defined when given any String value that does not conform to the Date Time String Format"_](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date-constructor) Why are you parsing `"best-of-5"` as if it was a date? – jonrsharpe Apr 26 '23 at 16:07
  • 1
    The `5` is being treated as the month number, so it's May 1. You're getting April 30 because of the time zone conversion. – Barmar Apr 26 '23 at 16:11
  • @jonrsharpe I have a code that tries to `Date.parse` unknown strings trying to figure out what's their type – Tomasz Cichociński Apr 26 '23 at 16:11
  • @Barmar but why it's 2001? – Tomasz Cichociński Apr 26 '23 at 16:11
  • I think everything else is being defaulted from a baseline date. – Barmar Apr 26 '23 at 16:12
  • `new Date("04-20")` returns April 20, 2001. – Barmar Apr 26 '23 at 16:13
  • 1
    Note a [mre] would be `new Date("5")`, the rest is being ignored. This is why everything you read strongly recommends not passing anything but a [Date Time String Format](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date-time-string-format) (i.e. ISO8601, `YYYY-MM-DDTHH:mm:ss.sssZ`) without being explicit about how it should be parsed! – jonrsharpe Apr 26 '23 at 16:13
  • @TomaszCichociński that's a losing proposition in Javascript, which applies type conversion liberally and constantly. You almost certainly want to look at the system that's accepting those strings, and put some kind of type _validation_ in front of that, rather than running type _inference_ much, much later. Or at the very least use type checkers that don't coerce/convert types (so don't use `Date`, but a real date validator that knows what format real dates can have and rejects things that don't match that) – Mike 'Pomax' Kamermans Apr 26 '23 at 16:14
  • 1
    [_"Enough making fun of languages that suck, let's talk about JavaScript."_](https://www.destroyallsoftware.com/talks/wat) – jonrsharpe Apr 26 '23 at 16:29
  • 2
    check soimon's answer here: https://stackoverflow.com/questions/65657805/chrome-javascript-engine-date-parsing-defaults-to-year-2001 – Mordy Stern Apr 26 '23 at 21:04

0 Answers0