// 获取日期
function getDay(d, num) {
const date = new Date(new Date(d).setDate(new Date(d).getDate() + num))
const year = date.getFullYear()
const month = (date.getMonth() + 1 + "").padStart(2, "0")
const day = (date.getDate() + "").padStart(2, "0")
return `${year}-${month}-${day}`
}
// 是否是闰年
function isLeap(year){
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
// 返回去年日期
function lastYearDate(d) {
const date = new Date(d)
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const lastYear = year - 1
const thisYearisLeap = isLeap(year)
const lastYearIsLeap = isLeap(lastYear)
// 特殊情况:去年是否是闰年 或 今年是闰年且为12月31日
if (lastYearIsLeap || (thisYearisLeap && month == 12 && day == 31)) return getDay(d, -366)
return getDay(d, -365)
}
// 测试
const date = "2021-2-10"
console.log(lastYearDate(date)) // 2020-02-10
const date1 = "2021-3-1"
console.log(lastYearDate(date1)) // 2020-02-29
const date2 = "2021-3-10"
console.log(lastYearDate(date2)) // 2020-03-09
const date3 = "2020-1-10"
console.log(lastYearDate(date3)) // 2019-02-10
const date4 = "2020-2-29"
console.log(lastYearDate(date4)) // 2019-03-01
const date5 = "2020-3-10"
console.log(lastYearDate(date5)) // 2019-03-11
const date7 = "2020-12-31"
console.log(lastYearDate(date7)) // 2019-12-31
const date6 = "2023-3-1"
console.log(lastYearDate(date6)) // 2022-03-01
JS获取去年日期(包含闰年逻辑)
于 2022-05-05 17:24:01 首次发布