Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 593
Abe Avatar asked Feb 03 '11 01:02

Abe


People also ask

How do you know if a month has 30 or 31 days JavaScript?

Given a month and the task is to determine the number of days of that month using JavaScript. 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.

How do I count the number of days in a month typescript?

To get the number of days in a month:Call the new Date() constructor, passing it 0 for the days. The method will return the date corresponding to the last day of the month. Call the getDate() method on the result to get the number of days in the month.

What is the keyword for extracting the day of the month in JavaScript?

Using the getUTCDate() Method All JavaScript getUTC() methods presumptively use local time for the Date. This function returns the date object's day of the month, ranging from 1 to 31. The day according to UTC, is returned by the getUTCDate() function.


2 Answers

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];
}
like image 123
Matti Virkkunen Avatar answered Oct 08 '22 02:10

Matti Virkkunen


Copy from another post: Get number days in a specified month using javascript?

//Month is 1 based
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

All the credits to @c_harm, really great solution

like image 36
David Sánchez Avatar answered Oct 08 '22 02:10

David Sánchez