javascript怎么根据月判定有多少天
时间:2022-02-23 17:51
方法:1、使用“new Date(year, month,0)”语句根据指定年份和月份来创建日期对象;2、使用“日期对象.getDate()”语句处理日期对象,返回指定月份的最后一天,即可知道指定月份有多少天。 本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。 javascript根据月判定有多少天的方法 要想得到某月有多少天,只需要获取到当月最后一天的日期就行了 方法1: 灵活调用 setMonth(),getMonth(),setDate(),getDate(),计算出所需日期 实现代码: 检测一下: 方法2: 原来还有更简单的办法:直接调用getDate() 检测一下: 【相关推荐:javascript学习教程】 以上就是javascript怎么根据月判定有多少天的详细内容,更多请关注gxlsystem.com其它相关文章!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")
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)