Conmi的正确答案——解决js的setMonth问题

IDE:idea
系统:WIN10 20H2
前端:elementUI

      /**
       * 设置本地月份
       * @param date 处理前日期
       * @param number 需要处理的月份(正负皆可,例如:+1就是加一个月)
       * @returns {Date|*}
       */
      localSetMonth(date, number) {
        const currentMonth = date.getMonth();

        // 获取传入月份的最大天数
        let tempDate1 = new Date();
        tempDate1.setDate(1);
        tempDate1.setMonth(currentMonth + 1);
        tempDate1 = new Date(tempDate1.getFullYear(), tempDate1.getMonth(), 0);
        const currentMonthMaxDate = tempDate1.getDate();

        // 获取处理后月份的最大天数
        let tempDate2 = new Date();
        tempDate2.setDate(1);
        tempDate2.setMonth(currentMonth + number + 1);
        tempDate2 = new Date(tempDate2.getFullYear(), tempDate2.getMonth(), 0);
        const afterHandlerMonthMaxDate = tempDate2.getDate();

        // 判断两个日期是否相等(就一定不会出现跳月的情况)
        if (currentMonthMaxDate === afterHandlerMonthMaxDate) {
          date.setMonth(date.getMonth() + number);
          return date;
        }

        // 如果两个月份不相等,则判断传入日期是否在月底,如果是月底则目标日期也设置为月底
        if (date.getDate() === currentMonthMaxDate) {
          tempDate2.setDate(afterHandlerMonthMaxDate);
          return tempDate2;
        }

        // 判断闰年
        if (date.getDate() >= afterHandlerMonthMaxDate) {
          tempDate2.setDate(afterHandlerMonthMaxDate);
          return tempDate2;
        }

        date.setMonth(date.getMonth() + number);
        return date;
      }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值