GibboK
GibboK

Reputation: 73908

How to list how many days for a month for a specific year?

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?

Upvotes: 6

Views: 553

Answers (4)

PleaseStand
PleaseStand

Reputation: 32052

You could, of course, just write a function based on what you already know, combined 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.

Upvotes: 3

basilikum
basilikum

Reputation: 10528

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;
}

Upvotes: 0

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

This will work too assuming Jan=1, Feb=2 ... Dec=12

function daysInMonth(month,year) 
{
   return new Date(year, month, 0).getDate();
}

FIDDLE

Upvotes: 3

Royi Namir
Royi Namir

Reputation: 148524

try 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

Upvotes: 9

Related Questions