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