tags:

views:

946

answers:

6

Hi,

Title says it all.

Say I have the month as a number and a year.

Malcolm

+4  A: 
function daysInMonth(Month, Year)
 {
     return 32 - new Date(Year, Month, 32).getDate();
 }

    daysInMonth(7,2009)
>>> 31
meder
Are you sure you pass 32 into the new Date bit??
Malcolm
Close, but the logic is off a bit. daysInMonth(2,2008) returns 31, for example. See my alternative below.
cpharmston
Yup, that moves it into the next month.. if you pass in 2009-07-32 it comes out at 2009-08-01. Take the date part and subtract it from 32 is 32 - 01 = 31 days in the previous month (i.e. the month we want)
Greg
@cpharmston that is correct - don't forget in Javascript 2 = March not Feb
Greg
Ah, of course, off by one error. Let this serve as a reminder to subtract 1 if you're taking user input :)
cpharmston
+7  A: 
function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}
daysInMonth(7,2009); //31
daysInMonth(2,2009); //28
daysInMonth(2,2008); //29
cpharmston
in Javascript months a 0-based, so while this seems right it is inconsistent with other javascript functions
Greg
Right. So use my function if you're parsing user input and soulscratch's function if you're using programmatic input.
cpharmston
A: 

The following takes any valid datetime value and returns the number of days in the associated month... it eliminates the ambiguity of both other answers...

 // pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
    return new Date(anyDateInMonth.getYear(), 
                    ++anyDateInMonth.getMonth(), 
                    0).getDate();}
Charles Bretana
+1  A: 
Date.prototype.monthDays= function(){
    var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
    return d.getDate();
}
kennebec
A: 
function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}

Have you tested the function for Feb 2012....it is a leap year and has 29 days...but the function shows 28 days...

Also u r welcome if you elaborate the New Date() and the format u r passing to it.....:)

Kanchan
+1  A: 

Another possible option would be to use Datajs

Then you can do

Date.getDaysInMonth(2009, 9)

Although adding a library just for this function is overkill, it's always nice to know all the options you have available to you :)

Zeus