Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is YYYY-MM-DD != YYYY/MM/DD [duplicate]

Tags:

javascript

In Chrome, we get some weirdness

> new Date("2014-01-01") - new Date("2014/01/01") < 3600000 

And this is because

new Date("2014-01-01") Wed Jan 01 2014 01:00:00 GMT+0100 (CET) 

while

new Date("2014/01/01") Wed Jan 01 2014 00:00:00 GMT+0100 (CET) 

Why do the '-' seem to add 1 hour to the time?

like image 549
Simon H Avatar asked Dec 02 '15 07:12

Simon H


1 Answers

I believe that the difference is caused by Date.parse adding UTC to one string but not the other, namely: / is not a legal separator in Date.parse() which means that UTC isn't added to the time once it's parsed. Because ' is a legal separator, it is parsed and then UTC is added to the returned time.

Date.parse is used by the new Date() method and its implementation is browser specific, I'm surprised this sort of thing doesn't come up more often.

The specification for Date.parse says:

The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

So I'd suggest either adding in a timezone manually before you parse, or discarding the time returned by new Date(), however that could lead to issues around midnight etc. The safest thing would be to see if you can get the date in a more specific format from both systems, with timezone information.

like image 147
JamesENL Avatar answered Oct 18 '22 23:10

JamesENL