开发者

How does this "days in month" function work?

  function GetDaysInMonth(month, year) 
  {
      return 32 - new Date(year, month, 32).getDate();
  }

Ok, I don't see what this is doing specifically, this part:

 new Date(year, month, 32).getDate();

I know what getDate() does, but then I looked up Date in JavaScrip开发者_开发技巧t but in this particular example, I don't see why you'd pass 32 here. How can this be returning the number of days in whatever month and year you're passing to it?


The "32nd day" of any month will roll over to the next one. If there are 31 days in a month, the "32nd day" will be the 1st of the next month. If there are 30, the "32nd day" will be the 2nd of the next month. If there are 28, the "32nd day" will be the 4th of the next month.

Subtract any of these from 32 and you get the correct number.


Date.prototype.monthDays: function(){
 var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
 return d.getDate();
}

The zero date of next month is the last date of this month...

alert(new Date().monthDays())// any date object


Try this:

function GetDaysInMonth(month, year) {
    return (new Date(new Date(year, month, 1, 0, 0, 0, 0)-86400000)).getDate();
}

This is using the first day of the preceeding month and substracts one day (86400000 milloseconds) from it to get the last day of the given month. Note that the Date’s month parameter expects values from 0 (January) to 11 (December). But for GetDaysInMonth use 1 (January) to 12 (December):

GetDaysInMonth(12, 2007) // returns 31
GetDaysInMonth(1, 2008) // returns 31
GetDaysInMonth(2, 2008) // returns 29

If you want to use the same values as for Date, use new Date(year, month+1, 1, 0, 0, 0, 0) instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜