根据年份和月份计算出该月份有多少天?2月的天数和是否闰年有关系,其他的月份天数是固定的,本来要考虑自己写代码去实现该功能,网上发现了更为简洁优雅的办法:
// 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
关于这种实现方法的原理解释:
Day 0 is the last day in the previous month. Because the month constructor is 0-based, this works nicely.
需要注意的是javascript中的月份是0-based的,2代表3月份,因此new Date(2009, 2, 0).getDate()计算的是2月份的天数。