Reputation: 5272
Why do I get 2 different dates with new Date()
when I pass a date vs. when I pass a date and time?
example:
Date.parse('2015-03-14')
// 1426291200000
new Date(1426291200000)
// Fri Mar 13 2015 17:00:00 GMT-0700 (PDT)
Date.parse('2015-03-14 00:00:00')
// 1426316400000
new Date(1426291400000)
// Fri Mar 13 2015 17:03:20 GMT-0700 (PDT)
Upvotes: 0
Views: 66
Reputation: 224
Sorry but I cannot comment yet. The string
you pass in Date.parse()
must follow the
ECMAScript 5 ISO-8601 format support .Reference link here
According to that, you the format of Date with time must be: '2015-03-14T00:00:00'
instead of '2015-03-14 00:00:00'
.
And since the time of Date.parse('2015-03-14')
is at GMT+00 but Date.parse('2015-03-14T00:00:00')
is at your time zone so if you add timezone GMT+00 to the second two time will be equal:
Date.parse('2015-03-14');
Date.parse('2015-03-14T00:00:00+00:00');
//1426291200000
Upvotes: 3
Reputation: 147473
Why do I get 2 different dates with new Date() when I pass a date vs. when I pass a date and time?
Because parsing strings with the Date constructor (and Date.parse, they are equivalent) is largely implementation dependent and therefore strongly recommended against.
Date.parse('2015-03-14') // 1426291200000 new Date(1426291200000) // Fri Mar 13 2015 17:00:00 GMT-0700 (PDT)
ISO 8601 format dates are treated as UTC in browsers compliant with ES5 and later (and UTC, local or invalid by earlier implementations), however not all browsers are compliant. Also, the specified behaviour is inconsistent with ISO 8601, which specifies that dates without a time zone are to be treated as local.
Date.parse('2015-03-14 00:00:00') // 1426316400000 new Date(1426291400000) // Fri Mar 13 2015 17:03:20 GMT-0700 (PDT)
The string '2015-03-14 00:00:00' is not compliant with ISO 8601, therefore parsing is entirely implementation dependent and may be treated as UTC, local or invalid. If made compliant with the addition of a "T":
"2015-03-14T00:00:00"
it should be treated as local (noting the previously mentioned caveat about non–compliant implementations).
It is very strongly recommended that you always manually parse strings. Use a library, one of the many good parsers that are around or just write your own function, 2 or 3 lines should suffice.
Upvotes: 1