[removed] calculate number of days in month for a

2019-01-14 04:16发布

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.

8条回答
甜甜的少女心
2楼-- · 2019-01-14 04:52

You can play with date objects:

var monthStart = new Date(year, month, 1);
var monthEnd = new Date(year, month + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24)

Arithmetic with Date objects gives a number of milliseconds.

This will even work for December; the Date constructor handles out-of-range arguments by wrapping around.

Note that month is zero-based (it must be between 0 and 11)

查看更多
Explosion°爆炸
3楼-- · 2019-01-14 04:53

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

查看更多
登录 后发表回答