获取N月前的日期

JavaScript实现日期范围计算

业务场景中总会遇到一些,日期范围为3个月,6个月,一年等等

比如:今天2024-11-06

3个月前日期:2024-08-06

6个月前日期:2024-05-06

一年前日期:2023-11-06

今天:2024-02-29

一年前:2月份没有29号,只能是2023-02-28

代码实现:

const getMouthAgo = (date, n) => {
  let strDaysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  let strYear = date.getFullYear()
  let strDay = date.getDate()
  let strMonth = date.getMonth() + 1
  // 一、解决闰年平年的二月份天数   //平年28天、闰年29天//能被4整除且不能被100整除的为闰年,或能被100整除且能被400整除

  if ((strMonth - n) > 0) {
    strMonth = strMonth - n
  } else {
    strMonth = strMonth - n + 12
    strYear -= 1
  }
  if ((strYear % 4) === 0 && ((strYear % 100) !== 0 || (strYear % 400) === 0)) {
    strDaysInMonth[2] = 29
  }
  strDay = Math.min(strDay, strDaysInMonth[strMonth])// 三、前一个月日期不一定和今天同一号,例如3.31的前一个月日期是2.28;9.30前一个月日期是8.30

  if (strMonth < 10) { // 给个位数的月、日补零
    strMonth = '0' + strMonth
  }
  if (strDay < 10) {
    strDay = '0' + strDay
  }
  var datastr = strYear + '-' + strMonth + '-' + strDay
  return datastr
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值