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

Solution 1:

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:

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:

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.