`date.setMonth` causes the month to be set too high if `date` is at the end of the month

Solution 1:

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.

Solution 2:

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

Solution 3:

Months in JavaScript are represented from 0-11. Month 1 would be February which only has 28/29 days, so when you set the month to 1, it tries to auto-correct the date to March to make a date that makes sense (since Feb 31st, makes no sense). Try it out by using the toDateString function to see what I mean:

 var d = new Date('2013/01/31');
 d.setMonth(2);
 console.log(d.toDateString()); // outputs Match 3rd, 2013

A little weird perhaps, but not buggy.

Solution 4:

In javascript month is start from 0. Assume today is 02/04/2012, when you setMonth(1) it will try to set to feb. Since max day in feb is 28/29, it move to the next month (March, which is 2)