Answer quick. Do you know what date is being created here?
var year = '2009', month = '09', day = '01'; var date = new Date( parseInt(year), parseInt(month), parseInt(day) );
At first glance, it wouldn't surprising that someone guesseed September 1st 2009. However, I'd not be writing this post if that was the correct answer, right?
parseInt function: it
can parse strings with a numeric value in the decimal radix, but also in other radices. See the
//passing the radix explicitly parseInt('1011', 10); // ==> 1011 parseInt('1011', 2); // ==> 11 parseInt('1011', 8); // ==> 521 parseInt('1011', 16); // ==> 4113
and after I explained the default behavior of
you probaly understood the results shown above. Well, maybe the last one deserves
in the chosen radix, it stops right there and parses only the portion of the string that
comes before that digit. So, since we started
'0182' with a leading zero, the
octal radix is assumed. Then, because 8 is not a valid octal digit, only
will be parsed, which becomes 1.
parseIntcall. If you're extra paranoid, then always pass the radix.
Back to our original question
Armed with the clarification made above, we can expand our example like this:
//given: var year = '2009', month = '09', day = '01'; // then the following statement: var date = new Date( parseInt(year), parseInt(month), parseInt(day) ); //...is equivalent to: var date = new Date( 2009, 0, // ===> oopsie 1 );
Hmmm, a zero in the month parameter. Will we have an error here? No, here comes the second potential surprise of this post.
new Date(year, month, day), the
monthparameter, and only the month parameter is zero-based (0 to 11).
So, in case the tips and the picture in this text were not enough to help you guessing the date being created, here goes another completely gratuitous one with the answer.