// 获取今天 '2022-01-07'
const getToday = () => new Date().toJSON().substring(0, 10)
// 判读闰年
const isLeapYear = (y) => y % 4 == 0 && (y % 400 == 0 || y % 100 != 0)
// 获取上个月今天 '2022-01-07' => '2021-12-07'
const getLastMonthToday = (time) => {
const arr = time.split('-')
let [year, month, date] = arr
// 前一月跨年
if (month === '01') {
month = 12
year = year - 1
} else {
month = month - 1
// 处理'2022-03-31'上月
if (month == 2 && date > 28) {
date = this.isLeapYear(year) ? 29 : 28
} else if (date == 31) {
const monthOf30days = [4, 6, 9, 11] // 小月 30天
monthOf30days.includes(month) && (date = 30)
}
}
month = ('' + month).length == 1 ? '0' + month : '' + month
return `${year}-${month}-${date}`
}
const today = getToday() // return '2022-01-07'
const lastMonthToday = getLastMonthToday(today) // return '2021-12-07'
console.log(today, lastMonthToday) // '2022-01-07' '2021-12-07'
js获取上个月今天
最新推荐文章于 2024-05-21 14:15:14 发布