Why does javascript new Date add one hour depending on the format of date

I am a bit stumped as to why, given the same date, but in a different format Javascript alters the time by one hour.

new Date("1969-12-22")
Date Mon Dec 22 1969 01:00:00 GMT+0100 (Greenwich Mean Time)


new Date("1969/12/22")
Date Mon Dec 22 1969 00:00:00 GMT+0100 (Greenwich Mean Time)

Notice the time in the first example is one hour ahead of the time in the second, but the date is exactly the same, just in a different format.

The problem this gives me is that I am unable to use .getTime() to compare timestamps for equality.

Does anyone know why the extra hour?

2 thoughts on “Why does javascript new Date add one hour depending on the format of date”

  1. The first input is in ISO 8601 format, and more specifically, a date-only format. The MDN documentation says about this format:

    When the time zone offset is absent, date-only forms are interpreted as a UTC time

    The second input is not ISO format, and so its interpretation is heavily agent-dependent:

    If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm.

    With the time zone lacking, it is quite common that the date is then interpreted in the local time zone.

    The output is in your local time zone in both cases, hence there can be a difference for the first input, unless your time zone happens to be UTC.

    Reply

Leave a Comment