Get number days in a specified month using JavaScript? [duplicate]

Get number days in a specified month using JavaScript? [duplicate]

Possible Duplicate:
What is the best way to determine the number of days in a month with javascript?

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


Solution 1:

// Month here is 1-indexed (January is 1, February is 2, etc). This is
// because we're using 0 as the day so that it returns the last day
// of the last month, so you have to add 1 to the month number 
// so it returns the correct amount of days
function daysInMonth (month, year) {
    return new Date(year, month, 0).getDate();

// July
daysInMonth(7,2009); // 31
// February
daysInMonth(2,2009); // 28
daysInMonth(2,2008); // 29

Solution 2:

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

Solution 3:

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.getFullYear(), 

Solution 4:

Another possible option would be to use Datejs

Related:  Is there a way to curve / arc text using CSS3 / Canvas

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 🙂