the Date.getMonth() method has bug?

The getMonth() method returns the month (from 0 to 11) for the specified date, according to local time.

Note: January is 0, February is 1, and so on.


Let's break this down:

var d = new Date(); // date is now 2013-01-31
d.setMonth(1);      // date is now 2013-02-31, which is 3 days past 2013-02-28
x = d.getMonth();   // what to do, what to do, 3 days past 2013-02-28 is in March
                    // so, expect x to be March, which is 2

This is only an issue when the day value of d is greater than the maximum number of days in the month passed to setMonth(). Otherwise, it works as you'd expect.


Simplest solution to this is to add second argument to setMonth:

var d = new Date();
d.setMonth(8,1);
d.getMonth(); //outputs 8

http://www.w3schools.com/jsref/jsref_setmonth.asp

Date.setMonth(month,day)

day: Optional. An integer representing the day of month Expected values are 1-31, but other values are allowed:

0 will result in the last day of the previous month -1 will result in the day before the last day of the previous month If the month has 31 days:

32 will result in the first day of the next month If the month has 30 days:

32 will result in the second day of the next month

Tags:

Javascript