In chrome console,
new Date('2012 01 01')
output: Sun Jan 01 2012 00:00:00 GMT-0600 (Central Standard Time)
new Date(2012, 01, 01)
output:
Wed Feb 01 2012 00:00:00 GMT-0600 (Central Standard Time)
I’m really curious as to why this happens.
Anyone care to shed some light?
I think you meant these:
And the reason is that the second example above uses the version of the
Dateconstructor that accepts numbers, rather than a string, and month numbers in JavaScript start with 0 = January. Sonew Date(2012, 1, 1)(the leading0in your examples is technically an error, but most engines allow it and treat the number as octal) is February 1st 2012.The first version above uses the
Dateconstructor that takes a string and parses it, and when parsing a date string, month numbers typically start with 1 = January. Note that the string you’re asking Chrome to parse isn’t in any format defined by the spec, and other engines may not parse it. In fact, until ECMAScript 5, there was no defined date string format (theDateconstructor that accepted a string was defined as accepting whatevertoStringoutput, but neither was actually specified). ECMAScript 5 added a simplified version of ISO-8601. But in the wild, every engine in the last decade has supported date strings in the formyyyy/mm/dd(but not necessarily the now-specifiedyyyy-mm-dd).