jquery获取指定月分中天数的方法
墨初 Web前端 946阅读
在jquery中可以通过Date对象中的getDate()方法获取当月的天数,当然这不仅仅只是一种方法,还可以通过其它的方法来获取指定月份的天数。
jquery获取月份天数的方法
方法1:
例:
function getMonthDay(year, month) {
let days = new Date(year, month + 1, 0).getDate()
return days
}
console.log(getMonthDay(2023,11));注意:个人测试此方法时有点问题,但网上很多人都在推荐这个方法。
方法2:
例:
function getDays(year, month) {
let days = [31,28,31,30,31,30,31,31,30,31,30,31]
if ((year % 4 ===0) && (year % 100 !==0 || year % 400 ===0) ) {
days[1] = 29
}
return days[month]
}
console.log(getDays(2023, 08));注意:
1、定义一个数组分别定义好每个月分的天数
2、上面的方法是通过数组获取当月的天数
3、上面的示例可以判断是不是闰年