js根据当天日期获取日期范围前几天或后几天

记录日常使用1

1.封装方法

getDaysBeforeAfter(dateStr, days) {
  // 获取时间范围
  const date = new Date(dateStr);
  date.setDate(date.getDate() + days);
  return date.toISOString().split("T")[0];
},

2.使用

timeFiltering(index) {
      // 时间筛选
      // this.activeIdx = index;
      const date = new Date();
      const todayDate =
        date.getFullYear() +
        "-" +
        Number(date.getMonth() + 1) +
        "-" +
        date.getDate();
      let time = this.timeList[index];
      switch (time) {
        case "24小时":
          this.formData.startDate = todayDate;
          this.formData.endDate = this.getDaysBeforeAfter(todayDate, 1);
          break;
        case "今天":
          this.formData.startDate = todayDate;
          this.formData.endDate = todayDate;
          break;
        case "昨天":
          this.formData.startDate = this.getDaysBeforeAfter(todayDate, -1);
          this.formData.endDate = todayDate;
          break;
        case "3天":
          this.formData.startDate = this.getDaysBeforeAfter(todayDate, -3);
          this.formData.endDate = todayDate;
          break;
        case "7天":
          this.formData.startDate = this.getDaysBeforeAfter(todayDate, -7);
          this.formData.endDate = todayDate;
          break;
        case "15天":
          this.formData.startDate = this.getDaysBeforeAfter(todayDate, -15);
          this.formData.endDate = todayDate;
          break;
        case "自定义":
          break;
        default:
          this.formData.startDate = "";
          this.formData.endDate = "";
          break;
      }
      // this.getList();
    },