0

我正在使用下面的代码来检查月份中的哪一天,但它不起作用。请帮助我

  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());
     }
  };

是小提琴。它返回给我不正确的结果..

4

3 回答 3

1
于 2012-12-15T13:20:09.270 回答
1

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 );
};
于 2012-12-15T13:30:26.090 回答
0

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);​
于 2012-12-15T13:23:52.800 回答