skip to Main Content

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


  1. That’s due to Date being sensitive to the input you provide it, the space contributed as well; try this:

    Date.parse("0001-01-01T00:00:00Z");
    

    This sets the time in UTC, whereas the space glitched and converted it to local time.

    Login or Signup to reply.
  2. 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')).

    Login or Signup to reply.
  3. 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:

    new Date(Date.parse('0001-02-03 04:05:06'))
    // 2003-01-02T04:05:06.000Z
    

    (The results depend on the local timezone.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search