51
votes

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?

3
Mine is adding 2, and I'm GMT+2JNF
Bascially I have two different feeds of data, and I wanted to check that the end date of one feed was equal to the beginning of the next. One has one format, the other has the other. So when I started checked that 1st - 2nd == 0 I was not getting any True. I can control for this of course but it mkaes life more complicatedSimon H
Did you have a look at this: stackoverflow.com/q/15109894/2357233 Might help youJamesENL
perhaps useful seems like slashes are not to spec?steveax
48 upvotes for a dupe. smhLightness Races in Orbit

3 Answers

26
votes

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.

12
votes

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.

1
votes

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.