JavaScript获取某月的天数

2019-05-17  本文已影响0人  小小的开发人员

JS提供了直接获取某月的天数的方法,没必要再判断闰年、平年获取2月的天数。

// 获取某月的天数
function getDaysInOneMonth (date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const d = new Date(year, month, 0)
    return d.getDate()
}
console.log(getDaysInOneMonth(new Date('2019/1/1'))) // 31
console.log(getDaysInOneMonth(new Date('2019/2/1'))) // 28
console.log(getDaysInOneMonth(new Date('2019/3/1'))) // 31
console.log(getDaysInOneMonth(new Date('2019/4/1'))) // 30

使用Date类的时候,还有一些需要注意的地方

let date = new Date('2019/5/19') // 这是星期天
console.log(date.getMonth()) // 4
console.log(date.getDay()) // 0 
上一篇 下一篇

猜你喜欢

热点阅读