tags:

views:

156

answers:

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

+10  A: 

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.

Jim Puls
so lets say I pass in Feb for 2009. Ok, then passing in 32 should give me 4 with that GetDate(). And then you take 32-4...is that correct? Ok why then do I get 31 back still for Feb
CoffeeAddict
the method doesn't even work for Feb
CoffeeAddict
32 - new Date(2009,1,32).getDate()returns28for me. Remember, months are zero-based.
Jim Puls
A: 

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.

Gumbo
I don't get yours, what's all the 1,0,0,... and the -864000
CoffeeAddict
@coffeeaddict: Read the manual: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date
Gumbo
+1  A: 
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

kennebec