Reputation: 8389
I am using the below code to check the day of the month but it is not working. Please help me on this
function daysInMonth(month, year) {
var length = new Date(year, month, 0).getDate();
for(var i = 1; i < = length; i++)
{
console.log(new Date(year,month,i).getDay());
}
};
here is the fiddle. It returns me incorrect results..
Upvotes: 0
Views: 254
Reputation: 15895
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 );
};
Upvotes: 1
Reputation: 66404
The Date
constructor takes param month as an integer between 0
and 11
, so your fiddle, which uses daysInMonth(12,2012);
is actually finding the days of the week in daysInMonth(0,2013);
, i.e. January 2013 not December 2012.
Here is some code that will make it work letting you use months as 1
to 12
function daysInMonth(month, year) {
var i, length = new Date(year, month, 0).getDate(); // get last day no. of previous month ( month 0 - 11 )
month = month - 1; // set month int to what we want
for (i = 1; i <= length; i++) {
console.log(new Date(year,month,i).getDay()); // continue as before
}
};
daysInMonth(12,2012);
Upvotes: 1
Reputation: 26940
This works:
console.log(new Date('12/15/2012').getDay());
Paul S. was right, works like this:
console.log(new Date(2012, 11, 15));
Appears that months start from 0, in your example:
daysInMonth(11,2012);
Upvotes: 0