javascript怎么根据月判定有多少天

javascript根据月判定有多少天的方法
要想得到某月有多少天,只需要获取到当月最后一天的日期就行了
方法1:
灵活调用 setMonth(),getMonth(),setDate(),getDate(),计算出所需日期
实现代码:
function getMonthLength(date) {
let d = new Date(date);
// 将日期设置为下月一号
d.setMonth(d.getMonth()+1);
d.setDate('1');
// 获取本月最后一天
d.setDate(d.getDate()-1);
return d.getDate();
}检测一下:
getMonthLength("2020-02-1")
getMonthLength("2021-02-1")
getMonthLength("2022-02-1")
getMonthLength("2022-03-1")
方法2:
原来还有更简单的办法:直接调用getDate()
function getMonthLength(year,month) {
return new Date(year, month,0).getDate();
}检测一下:
getMonthLength(2020,02) getMonthLength(2021,02) getMonthLength(2022,02) getMonthLength(2022,03) getMonthLength(2022,04)

【相关推荐:javascript学习教程】
javascript