JS获取去年日期(包含闰年逻辑)

// 获取日期
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
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值