JavaScript getDate() Method: This method returns the number of days in a month (from 1 to 31) for the defined date. Return value: It returns a number, from 1 to 31, representing the day of the month.
// 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
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
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();}
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With