时间计算当前日期x月之前日期计算方法记录

项目场景:

提示:用于计算月份日期,(当前日期一个月前的日期,当前日期两个月前的日期以此类推,考虑特殊月份了)


问题描述:

提示:下列时间计算适用于,月份计算(此方法是我注册成全局的了)
例如:传入1,返回结果就是当前日期一个月前的日期
在这里插入图片描述

export function InRecentMonthsAll(params) {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth() + 1; // 0-11表示1-12月
  var day = now.getDate();
  var dateObj = {};
  dateObj.now = year + '-' + month + '-' + day;
  var nowMonthDay = new Date(year, month, 0).getDate(); // 当前月的总天数
  let InRecentMonths = ''
  if (month - params <= 0) { // 如果是1、2、3月,年数往前推一年
    InRecentMonths = new Date((year - 1), (12 - (params - parseInt(month))), 0).getDate(); // X个月前所在月的总天数
    if (InRecentMonths < day) { // X个月前所在月的总天数小于现在的天日期
      dateObj.last = (year - 1) + '-' + (12 - (params - month)) + '-' + InRecentMonths;
    } else {
      dateObj.last = (year - 1) + '-' + (12 - (params - month)) + '-' + day;
    }
  } else {
    InRecentMonths = new Date(year, (parseInt(month) - params), 0).getDate(); // X个月前所在月的总天数
    if (InRecentMonths < day) { // X个月前所在月的总天数小于现在的天日期
      if (day < nowMonthDay) { // 当前天日期小于当前月总天数,2月份比较特殊的月份
          dateObj.last = year + '-' + (month - params) + '-' + (InRecentMonths - (nowMonthDay - day));
      } else {
          dateObj.last = year + '-' + (month - params) + '-' + InRecentMonths;
      }
    } else {
        dateObj.last = year + '-' + (month - params) + '-' + day;
    }
  }
  return dateObj;
}

结果:

在这里插入图片描述


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值