Creating date with numbers (new Date(2012, 03, ...) gives wrong month (+1)
When creating a new Date
object using numbers for the parts, the value I get back is exactly one month ahead of the value I put in for 'month'.
new Date(2012, 05, 17, 00, 00, 00)
Sun Jun 17 2012 00:00:00 GMT+0800 (HKT) // june?!
However, a normal parse of exactly the same string returns the correct time:
new Date("2012-05-17 00:00:00")
Thu May 17 2012 00:00:00 GMT+0800 (HKT)
I get the same result in ie/ff/chrome. Removing hours/min/seconds doesn't have any effect. I can work around it by subtracting one before setting the month, but instead I just switched to writing out my date as a string.
Edit: The string parse doesn't work in IE. I have no idea what I did, but I swear I made that work. Thats prob. why I avoided it in the first place. I've switched to using moment.js for now.
Ah, now I get it. Just like regular java dates, which I don't code in except rarely, and even then always with a library (joda, etc). What a terrible idea anyway. Here is skeets take on the question: Why is January month 0 in Java Calendar?
Why is this happening?
Solution 1:
Programmers start counting from 0. So months are represented by 0(Jan)-11(Dec).
The reason days don't follow this rule is to not confuse authors with 30/31 month differences.
From MDN:
month
Integer value representing the month, beginning with 0 for January to 11 for December.