笨方法:各种if判断,判断闰年,判断闰月啊之类的
思路:Date API 处理日期溢出时,会自动往后推延响应时间的规则
// month 值需对应实际月份减一,如实际 2 月,month 为 1,实际 3 月,month 为 2
function getMonthCountDay (year, month) {
return 32 - new Date(year, month, 32).getDate()
}
// 求闰年的 2 月份总天数
getMonthCountDay(2000, 1) // 29
// 求 1 月份总天数
getMonthCountDay(2000, 0) // 31
getMonthCountDay(2001, 0) // 31
// 求 4 月份总天数
getMonthCountDay(2000, 3) // 30
getMonthCountDay(2001, 3) // 30
类似方式
function getMonthCountDay (year, month) {
return new Date(year, month + 1, 0).getDate()
}
Date API 处理日期溢出时,会自动往后推延响应时间的规则?
- new Date(2019, 0, 50)其中0代表1月,1月只有31天,则多出来的19天会被加到2月,结果是2019年2月19日。
- new Date(2019, 20, 10),1年只有12个月,多出来的9个月会被加到2020年,结果是2020年9月10日
- new Date(2019, -2, 10),2019年1月10日往前推2个月,结果为2018年11月10日
- new Date(2019, 2, -2),2019年3月1日往前推2天,结果为2019年2月26日