How to list how many days for a month for a specific year in JavaScript?
As we know 30 days have September, April, June, and November. All the rest have 31, Except February, Which has 28 days clear, And 29 in each leap year.
I would need take count of leap year. Do you know any native way to fond out.. or maybe a library.. could you suggest one?
How to list how many days for a month for a specific year in JavaScript?
As we know 30 days have September, April, June, and November. All the rest have 31, Except February, Which has 28 days clear, And 29 in each leap year.
I would need take count of leap year. Do you know any native way to fond out.. or maybe a library.. could you suggest one?
Share Improve this question asked Jul 24, 2013 at 13:56 GibboKGibboK 74k147 gold badges451 silver badges674 bronze badges 04 Answers
Reset to default 9try this
function daysInMonth(m, y)
{
m=m-1; //month is zero based...
return 32 - new Date(y, m, 32).getDate();
}
usage :
>> daysInMonth(2,2000) //29
This will work too assuming Jan=1, Feb=2 ... Dec=12
function daysInMonth(month,year)
{
return new Date(year, month, 0).getDate();
}
FIDDLE
You could, of course, just write a function based on what you already know, bined with the logic for leap years:
// m is the month (January = 0, February = 1, ...)
// y is the year
function daysInMonth(m, y) {
return m === 1 && (!(y % 4) && ((y % 100) || !(y % 400))) ? 29
: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m];
}
Years divisible by 4 but not divisible by 100 except if divisible by 400 are leap years.
There are probably native ways to find out, but I think it's nice to know, that the leap year algorithm is actually not so hard to implement by oneself:
function isLeapYear(year) {
if (year % 400 === 0) {
return true;
} else if (year % 100 === 0) {
return false;
} else if (year % 4 === 0) {
return true;
}
return false;
}