js 时间处理函数

getNextMonth (date, months) { // 从当前日期延后months个月
          let arr = date.split('-')
          let year = arr[0], month = arr[1], day = arr[2]
          let days = new Date(year, month, 0)
          days = days.getDate() // 获取当前日期中的月的天数
          let year2 = year, month2 = parseInt(month) + parseInt(months)
          if (month2 > 12) {
            year2 = parseInt(year2) + 1
            month2 = month2 - 12
          }

          let day2 = day
          let days2 = new Date(year2, month2, 0)
          days2 = days2.getDate()
          if (day2 > days2) {
            day2 = days2
          }
          if (month2 < 10) {
            month2 = '0' + month2
          }
          let t2 = year2 +'-'+ month2 +'-'+ day2
          return t2
        },
getNextMonth(date, months) { // 从当前日期延后months个月再减一天
      // console.log("getNextMonth", date, months);
      let arr = date.split("-");
      let year = arr[0],
        month = arr[1],
        day = arr[2];
      let days = new Date(year, month, 0);
      days = days.getDate(); // 获取当前日期中的月的天数
      let year2 = year,
        month2 = parseInt(month) + parseInt(months);
      if (month2 > 12 && parseInt(month2)%12!=0) {
        year2 = parseInt(year2) + Math.floor(month2/12);
        month2 = parseInt(month2)%12;
      } else if (month2 > 12 && parseInt(month2)%12===0) {
        year2 = parseInt(year2) + Math.floor(month2/12) - 1
        month2 = 12
      }
      if (month2 < 10) {
        month2 = "0" + month2;
      }

      let t2
      let day2 = day;
      let days2 = new Date(year2, month2, 0); // 表示当前月的最后一天
      days2 = days2.getDate();
      if (day2 > days2) {
        day2 = days2;
        t2 = year2 + "-" + month2 + "-" + day2;
      } else {
        t2 = year2 + "-" + month2 + "-" + day2;
        t2 = this.getPreDate(t2);
      }
      return t2;
    },

        getPreDate (date) { // 从当前日期前一天
          let d = new Date(date)
          d = +d - 1000*60*60*24
          d = new Date(d)
          return formatDate(d, 'yyyy-MM-dd')
        },
        getNextDate (date) {  // 从当前日期后一天
          let d = new Date(date)
          d = +d + 1000*60*60*24
          d = new Date(d)
          return formatDate(d, 'yyyy-MM-dd')
        }

 

posted @ 2022-03-01 17:35  front-gl  阅读(103)  评论(0编辑  收藏  举报