Here's my experiment:
> new Date('2011-02-1')
2011-02-01T08:00:00.000Z
> new Date('2011-02-01')
2011-02-01T00:00:00.000Z
Does anybody know why there are 8 hours difference between the two?
Thanks!
Here's my experiment:
> new Date('2011-02-1')
2011-02-01T08:00:00.000Z
> new Date('2011-02-01')
2011-02-01T00:00:00.000Z
Does anybody know why there are 8 hours difference between the two?
Thanks!
This is actually up to the browser or JavaScript runtime implementation to determine what happens. The Date
constructor conforms to the format YYYY-MM-DDTHH:mm:ss.sssZ
which is a simplification of ISO 8601 Extended Format. If parsing that fails, it is implementation-specific what happens.
Essentially, since you failed to specify DD
for 2011-02-1
, it's up to the browser to call the shots on what you'll get. For example, in Google Chrome and Firefox I get 2011-02-01T00:00:00.000Z
yet in Safari I just get an error, Invalid Date
.
See the ECMAScript 5 specification:
[…] the value produced by
Date.parse
is implementation-dependent when given any String value that does not conform to the Date Time String Format (15.9.1.15) and that could not be produced in that implementation by thetoString
ortoUTCString
method.
Note that the Date
constructor uses the same parsing algorithm as Date.parse
. This is why it's highly discouraged to use a string for the constructor. Use the multi-argument version that is standardized. See MDN.