Javascript: calculate number of days in month for a given year

Abe picture Abe · Feb 3, 2011 · Viewed 38.2k times · Source

I have a HTML page with 3 dropdowns for the month, day and year and I was wondering if there was a way to populate the month drop down properly depending on the month and year.

I haven't done this before on the client side, but it looks like a lot of controls like the jQuery DatePicker are doing that behind the scenes.

Answer

Matti Virkkunen picture Matti Virkkunen · Feb 3, 2011

As far as I know, there's no (neat) built-in function for that. I wrote this once:

// note that month is 0-based, like in the Date object. Adjust if necessary.
function getNumberOfDays(year, month) {
    var isLeap = ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0));
    return [31, (isLeap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}