js realizes the calculation of adding and subtracting months from year to month (pure native realization of the year and month before and after n months of the current year)

  1. Not much to say, when you encounter a requirement: let you calculate before or after n months (that is, yyyy-mm + n) of a certain year and month, without plug-ins, are you confused and unable to start? Based on the summary of self-development, we provide you with a solution to achieve this requirement.
        /*
          计算年月加减月份
          originalYtd为String,格式为"yyyy-MM"
          monthNum为Number,格式为n,n为正数表示加月份,为负数表示减月份
        */
    
        function calcMonths(originalYtd, monthNum) {
          let arr = originalYtd.split('-');
          let year = parseInt(arr[0]);
          let month = parseInt(arr[1]);
          month = month + monthNum;
          if (month > 12) {
            let yearNum = parseInt((month - 1) / 12);
            month = month % 12 == 0 ? 12 : month % 12;
            year += yearNum;
          } else if (month <= 0) {
            month = Math.abs(month);
            let yearNum = parseInt((month + 12) / 12);
            let n = month % 12;
            if (n == 0) {
              year -= yearNum;
              month = 12
            } else {
              year -= yearNum;
              month = Math.abs(12 - n)
            }
    
          }
          month = month < 10 ? "0" + month : month;
          return year + "-" + month;
        }

     

  2. Of course, in addition to the above pure native js implementation, the moment.js plug- in official website portal is a processing method with high frequency and efficiency in actual development. The previous article also taught its use in Vue and summarized nearly 20 common date processing. moment.js usage and summary .
  3. The code word is not easy, please ask the big guys from all walks of life to do more and more.

Guess you like

Origin blog.csdn.net/Yi2008yi/article/details/123182687