Here's the correct code:
function daysInMonth( month, year ) {
var day;
for( var i = 1 ; i <= new Date( year, month, 0 ).getDate() ; i++ ) {
day = new Date( year, month-1, i );
console.log( day, day.getDay() );
}
};
daysInMonth( 12, 2012 );
The issue was due to the fact that months are indexed 0-11. Provided that first day of the week is Sunday:
daysInMonth( 12, 2012 );
Sat Dec 01 2012 00:00:00 GMT+0100 (CET) 6 //Sat
Sun Dec 02 2012 00:00:00 GMT+0100 (CET) 0 //Sun
Mon Dec 03 2012 00:00:00 GMT+0100 (CET) 1 //Mon
...
Mon Dec 31 2012 00:00:00 GMT+0100 (CET) 1 //Mon
Alternative, shorter code:
function daysInMonth( month, year ) {
for( var i = new Date( year, month, 0 ).getDate(), d = new Date( year, month-1, 1 ).getDay() ; i-- ; )
console.log( d++ % 7 );
};