Why is YYYY-MM-DD != YYYY/MM/DD

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Quoting from V8 source code.

The comments from this function

bool DateParser::Parse(Vector<Char> str,
                       FixedArray* out,
                       UnicodeCache* unicode_cache)

> Accept ES5 ISO 8601 date-time-strings or legacy dates compatible with Safari.

> ES5 ISO 8601 dates:

> [('-'|'+')yy]yyyy[-MM[-DD]][THH:mm[:ss[.sss]][Z|(+|-)hh:mm]]

> A string that matches both formats (e.g. 1970-01-01) will be parsed as an ES5 date-time string - which means it will default to UTC time-zone. That's unavoidable if following the ES5 specification.

The dash (-) is correct notation for Date.

Solution 3 - Javascript

It is because of globalization. The dash ( - ) is not an English notation (GMT). Javascript parses the notation. Try setting the culture and then use the dash notation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimon HView Question on Stackoverflow
Solution 1 - JavascriptJamesENLView Answer on Stackoverflow
Solution 2 - JavascriptzangwView Answer on Stackoverflow
Solution 3 - JavascriptmarcokreeftView Answer on Stackoverflow