天天看点

date函数setMonth()方法 项目中遇到的坑

问题回顾

点击月份,可以切换月份,查询对应订单,

12月31日,近6个月的月份变成如下所示

date函数setMonth()方法 项目中遇到的坑

排查问题

月份计算通过取当前时间,调用addMonths方法获得,addMonths通过计算months,调用setMonth方法实现,在addMonths中打印setMonth的值。

index.vue片段:

monthOption: [
        {
          name: new Date().getMonth() + 1 + '月',
          color: '#1989fa',
          timeStr: new Date().format('yyyy-MM')
        },
        {
          name: new Date().addMonths(-1).getMonth() + 1 + '月',
          timeStr: new Date().addMonths(-1).format('yyyy-MM')
        },
        {
          name: new Date().addMonths(-2).getMonth() + 1 + '月',
          timeStr: new Date().addMonths(-2).format('yyyy-MM')
        },
        {
          name: new Date().addMonths(-3).getMonth() + 1 + '月',
          timeStr: new Date().addMonths(-3).format('yyyy-MM')
        },
        {
          name: new Date().addMonths(-4).getMonth() + 1 + '月',
          timeStr: new Date().addMonths(-4).format('yyyy-MM')
        },
        {
          name: new Date().addMonths(-5).getMonth() + 1 + '月',
          timeStr: new Date().addMonths(-5).format('yyyy-MM')
        }
      ]复制代码      

prototype.js片段:

Object.defineProperty(Date.prototype, 'addMonths', {
  value: function(months) {
    if (months === undefined || months === '') {
      months = 1
    }
    console.log(this.getMonth(),months)
    this.setMonth(this.getMonth() + months)
    return this
  }
})复制代码      

打印结果

new Date(new Date('2020-12-31').addMonths(-1)).format('yyyy-MM-dd') //  11 -1 "2020-12-01"
new Date(new Date('2020-12-31').addMonths(-2)).format('yyyy-MM-dd') //  11 -2 "2020-10-31"
new Date(new Date('2020-12-31').addMonths(-3)).format('yyyy-MM-dd') //  11 -3 "2020-10-01"
new Date(new Date('2020-12-31').addMonths(-4)).format('yyyy-MM-dd') // 11 -4 "2020-08-31"
new Date(new Date('2020-12-31').addMonths(-5)).format('yyyy-MM-dd') // 11 -5 "2020-07-31"
new Date(new Date('2020-12-31').addMonths(-6)).format('yyyy-MM-dd') // 11 -6 "2020-07-01"
new Date(new Date('2020-12-31').addMonths(-7)).format('yyyy-MM-dd') // 11 -7 "2020-05-31"
new Date(new Date('2020-12-31').addMonths(-8)).format('yyyy-MM-dd') // 11 -8 "2020-05-01"
new Date(new Date('2020-12-31').addMonths(-9)).format('yyyy-MM-dd') // 11 -9 "2020-03-31"
new Date(new Date('2020-12-31').addMonths(-10)).format('yyyy-MM-dd') // 11 -10 "2020-03-02"
new Date(new Date('2020-12-31').addMonths(-11)).format('yyyy-MM-dd') // 11 -11 "2020-01-31"
new Date(new Date('2020-12-31').addMonths(-12)).format('yyyy-MM-dd') // 11 -12 "2019-12-31"
new Date(new Date('2020-12-31').addMonths(-10)).format('yyyy-MM-dd') // 11 -10 "2020-03-02"复制代码      

通过上图的打印结果,可以发现,this.getMonths()和传入的计算months输出无误,那么问题发生在setMonth的时候。上网查阅mdn资料,发现如下描述:

点击快速跳转 Date.prototype.setMonth()方法

If a parameter you specify is outside of the expected range, setMonth() attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1, and 3 will be used for month.

The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st August 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.

如果指定的参数超出预期范围,setMonth()会尝试相应地更新date对象中的日期信息。例如,如果monthValue使用15,year将增加1,month将使用3。

每月的当前日期将对该方法的行为产生影响。从概念上讲,它将在指定为参数的新月份的第一天添加当前日期所给出的天数,以返回新的日期。例如,如果当前值是2016年8月31日,用值1调用setMonth将返回2016年3月2日。这是因为2016年2月有29天。

推理到我们项目中。在12月31日当天。调用addMonths(-1),相当于调用setMonth(10,31)方法。由于11月只有30天,11月添加31天,天数溢出后。结果就会推后一天,到12月1日。

项目上线方案:

function addMonth(date, months) {
  var y = date.getFullYear()
  var m = date.getMonth()
  var d = date.getDate()

  y += Math.floor((m + months) / 12) //计算年
  m = Math.floor((m + months) % 12) + 1 //计算月
  if (m <= 0) {
    m += 12
  }
  var d_max = new Date(y , m  ,'0').getDate() //获取计算后的月的最大天数
  if (d > d_max) {
    d = d_max
  }
  return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d)
}
addMonth(new Date('2020-12-31'),2)复制代码      
get(mom, 'Month') + months * isAdding)
function mod(n, x) {
     return ((n % x) + x) % x;
}
function daysInMonth(year, month) {
    if (isNaN(year) || isNaN(month)) {return NaN;}
    var modMonth = mod(month, 12);year += (month - modMonth) / 12;
        return modMonth === 1
        ? isLeapYear(year)
        ? 29
        : 28
        : 31 - ((modMonth % 7) % 2);
}
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
mom._d['setMonth'](value, dayOfMonth);复制代码