2

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?

PrestonDocks
  • 4,851
  • 9
  • 47
  • 82
  • So I have found a way to allow me to check the equality of `.getTime()` `new Date("1969-12-22" + " 00:00:00")`. It is annoying though, that I would have to do this. – PrestonDocks Feb 15 '21 at 20:24
  • 1
    You clearly time-traveled that's all, nothing to see here! On further note, I am curious what's up. – BGPHiJACK Feb 15 '21 at 20:25
  • Oh it appears it may be a time-zone difference in that format? I'm getting 0:00 and 5:00 . I am -5GMT – BGPHiJACK Feb 15 '21 at 20:29
  • 1
    I've dealt with this little but I'd watch this and maybe do a regex.replace on the string ahead of time to replace / with - or the other way around which ever is easiest. – BGPHiJACK Feb 15 '21 at 20:32

1 Answers1

4

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.

trincot
  • 317,000
  • 35
  • 244
  • 286