zoukankan      html  css  js  c++  java
  • 动态获取近三年的所有月份,作为下拉框选项

     

    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自行修改,逻辑不变

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

  • 相关阅读:
    css 弹出框
    net stop 出现1060错误
    a href=#与 a href=javascript:void(0) 的区别
    ubuntu如何安装Mac主题
    js arguments.callee & caller的用法及区别
    js函数——setinterval和setTimeout
    highcharts简介
    highcharts柱状图和饼图的数据填充
    jqgrid的外观重绘
    laravel定时任务
  • 原文地址:https://www.cnblogs.com/CatcherLJ/p/11207553.html
Copyright © 2011-2022 走看看