I’m experiencing this issue in both Node.js v16.20.2 and in a browser console:
> new Date(Date.parse('0001-01-01'))
0001-01-01T00:00:00.000Z
OK, I expected this. Now consider this:
> new Date(Date.parse('0001-01-01 00:00:00'))
2000-12-31T23:00:00.000Z
Year 2000?
This works just fine:
> new Date(Date.parse('0001-01-01T00:00:00Z'))
0001-01-01T00:00:00.000Z
I know how to fix it and I also know how dates should be parsed, but I’m looking for an explanation of why this behavior happens.
3
Answers
That’s due to Date being sensitive to the input you provide it, the space contributed as well; try this:
This sets the time in UTC, whereas the space glitched and converted it to local time.
Why did you add a space in
Date.parse()
? It causes the problem. Your code should look like this:new Date(Date.parse('0001-01-01'))
.As pointed out in the comments, the format with the space is non-standard so all bets are off.
It looks like it’s being parsed as
MM-DD-YY HH:MM:SS
:(The results depend on the local timezone.)