Reputation: 257
I tried to make Date object from string in javascript, but i see javascript parse date string very strange here.
> new Date("2012-01-01");
Sun Jan 01 2012 07:00:00 GMT+0700 (ICT)
> new Date("01-01-2012");
Sun Jan 01 2012 00:00:00 GMT+0700 (ICT)
> new Date("2012-01-01") == new Date("01-01-2012")
false
I use Chrome 32, as you can see they are 7 hour differ. Please tell me what happend here?
Upvotes: 15
Views: 1761
Reputation: 147343
The reason for the difference is explained in other answers. A good way to avoid the issue is to parse the string yoruself. If you want 2012-01-01 to be treated as UTC then:
function dateFromUTCString(s) {
var s = s.split(/\D/);
return new Date(Date.UTC(s[0], --s[1], s[2]));
}
If you want to treat it as a local date, then:
function dateFromString(s) {
var s = s.split(/\D/);
return new Date(s[0], --s[1], s[2]);
}
Upvotes: 3
Reputation: 1418
It's all about how the browser implements Date.parse
(spec). That method is called on the string passed into the Date
constructor (spec) and first tries to match the string against a known format to determine what values are where. I'd expect different browsers implemented that decision tree in slightly different ways, but Chrome's implementation probably assumes that the "2012-01-01"
version is a prefix to the ISO-8601 standard which is based on Zulu, or GMT/UTC, and includes a timezone ("2012-01-01T00:00:00Z-07:00"
) while the "01-01-2012"
version is a localization based on your LOCAL time zone, and doesn't bother to specify it ("01-01-2012 00:00:00"
) so the 7 hour difference is based on the 7 hour offset between the ISO standard date and the localized date. Date.prototype.toString()
(spec), by contrast, is supposed to display local time and is returned by the Date
constructor, which is why it's localized in both return values from your test.
From the spec for Date.parse
:
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. Unrecognizable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN.
Meaning if you don't use the full ISO-8601 date specified in 15.9.1.15, the browser can make it up as it goes along or just give you NaN
. Even though this IS the standard, some browsers are notorious for not actually FOLLOWING standards, so you might consider just specifying all of the parameters unambiguously by parsing the data yourself and using the other Date
constructor (spec).
Upvotes: 16