admin管理员组

文章数量:1313797

  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 JavaScript 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?

  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 JavaScript 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?

Share Improve this question edited Nov 6, 2009 at 18:26 Jim Puls 81.1k10 gold badges75 silver badges78 bronze badges asked Nov 6, 2009 at 18:22 PositiveGuyPositiveGuy 47.8k112 gold badges314 silver badges479 bronze badges 2
  • actually it's returning 31 for february so the fing thing doesn't even work. I'm just pissed because my boss just tells me how to reduce 30 lines of code but then the fing function he tells me to use doesn't even work! Not that I can't fix it but you know how conceded asswipes are about code reviews sometimes. – PositiveGuy Commented Nov 6, 2009 at 18:45
  • I should have just looked up this method, it was stolen: snippets.dzone./posts/show/2099 – PositiveGuy Commented Nov 6, 2009 at 18:55
Add a ment  | 

3 Answers 3

Reset to default 12

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.

本文标签: javascriptHow does this quotdays in monthquot function workStack Overflow