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?
The new Date() Constructor In JavaScript, date objects are created with new Date() . new Date() returns a date object with the current date and time.
new Date() : Creates a date object set to the current date and time.
Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.
We can create a date object by passing the Date object a timestamp number in milliseconds. For example, new Date(1572840117245) . When we create a date object by passing it 0 milliseconds, it will return the date object for Jan 01 1970 05:30:00 .
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With