动态获取近三年的所有月份,作为下拉框选项

 

initDateData() {
      const dateData = [];
      const date1 = new Date();//当前日期
      for (let i = 0; i < 36; i++) {//由于是3年 有36个月
        let cur = '';
        let tempYear = date1.getFullYear();//当前年份
        let tempMonth = date1.getMonth() - i + 1;//当前月份

     //最重要的代码
        if (tempMonth <= 0) {//tempMonth从0开始就是去年,前年,上前年……
      // 由于取的是Math.floor,所以要 -1,这里需要说明一下用Math.floor不用Math.ceil的原因是tempMonth为0时,是去年,因此需要-1。
       //如果是Math.ceil(0/-12)还是0,但使用了Math.ceil后就不能-1,就会有问题。
      tempYear = date1.getFullYear() - Math.floor(tempMonth / -12) - 1; 

      //tempMonth=0,12月,tempMonth=-1,11月,刚好是 tempMonth + n*12,1代表前n年,所以他是动态变化的。
      tempMonth += (Math.floor(tempMonth / -12) + 1) * 12;
        }
     //1-9月补0
        if (tempMonth < 10) {
          cur = `${tempYear}-0${tempMonth}`;
        } else {
          cur = `${tempYear}-${tempMonth}`;
        }
        dateData.push(cur);
      }
      return dateData;
    }

  

这个方法是在vue里面写的,如果是其他js自行修改,逻辑不变

如果文章对你有帮助,麻烦帮忙点个赞哦!嘿嘿!做一个靠谱的技术博主!

原文地址:https://www.cnblogs.com/CatcherLJ/p/11207553.html