Get number days in a specified month using JavaScript?

Javascript

Javascript Problem Overview


> 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.

Javascript Solutions


Solution 1 - Javascript

// Month in JavaScript is 0-indexed (January is 0, February is 1, etc), 
// but by using 0 as the day it will give us the last day of the prior
// month. So passing in 1 as the month number will return the last day
// of January, not February
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 - Javascript

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

Solution 3 - Javascript

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(), 
                    anyDateInMonth.getMonth()+1, 
                    0).getDate();}

Solution 4 - Javascript

Another possible option would be to use Datejs

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 :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMalcolmView Question on Stackoverflow
Solution 1 - Javascriptc_harmView Answer on Stackoverflow
Solution 2 - JavascriptkennebecView Answer on Stackoverflow
Solution 3 - JavascriptCharles BretanaView Answer on Stackoverflow
Solution 4 - JavascriptRYFNView Answer on Stackoverflow