Javascript getMonth() returns wrong value or setMonth() sets wrong value

Ichinisan

Lifer
Oct 9, 2002
28,298
1,235
136
Code:
var tempdate=new Date();
tempdate.setMonth(0);
alert("Month: "+tempdate.getMonth());
"Month: 0"



Code:
var tempdate=new Date();
tempdate.setMonth(1);
alert("Month: "+tempdate.getMonth());
"Month: 2"



Code:
var tempdate=new Date();
tempdate.setMonth(2);
alert("Month: "+tempdate.getMonth());
"Month: 2"



Code:
var tempdate=new Date();
tempdate.setMonth(3);
alert("Month: "+tempdate.getMonth());
}
"Month: 3"



I'm stumped.

0-January
1-February
2-March
3-April
4-May
5-June
6-July
7-August
8-September
9-October
10-November
11-December

Whenever I set the value to 1 (February), it always reads back a value of 2 (March). This is driving me insane!
 

Ichinisan

Lifer
Oct 9, 2002
28,298
1,235
136
Figured it out.

[edit]

Today is 2014-12-29, so changing only the month to 1 (February) would make it 2014-02-29. That's only a valid date on leap year, so the date is changed to 2014-03-01.

Code:
var tempdate=new Date();
tempdate.setMonth(1);
alert("Month: "+tempdate.getMonth());
"Month: 2" (2014-12-29 --> 2014-02-29 --> 2014-03-01)



Code:
var tempdate=new Date();
tempdate.setDate(1);
tempdate.setMonth(1);
alert("Month: "+tempdate.getMonth());
"Month: 1" (2014-12-29 --> 2014-02-01)
 
Last edited: