最近一个月 / 最近半年的时间填充日期, 不包含当天 / 当月

139 阅读1分钟
fillDateTime(type) {
      var endTime, temp, startTime, xlist, dayLen;
      var nowTime = new Date();
      if (type === 1) {
        //* 1 按天统计
        endTime = this.$dayjs(
          new Date(nowTime).setDate(nowTime.getDate()),
          "YYYY-MM-DD"
        );
        temp = new Date(new Date(nowTime).setMonth(nowTime.getMonth() - 1));
        startTime = this.$dayjs(
          temp.getFullYear() +
            "-" +
            (temp.getMonth() + 1) +
            "-" +
            temp.getDate(),
          "YYYY-MM-DD"
        );
        dayLen = Math.floor(
          (new Date(endTime).getTime() - new Date(startTime).getTime()) /
            86400000
        );
        xlist = new Array(dayLen).fill(0).map((item, index) => ({
          time: this.$dayjs(
            new Date(startTime).setDate(new Date(startTime).getDate() + index),
            "YYYY-MM-DD"
          )
        }));
      } else {
        //* 2 按月统计
        endTime = this.$dayjs(
          new Date(nowTime).setMonth(nowTime.getMonth() - 1),
          "YYYY-MM"
        );
        temp = new Date(new Date(nowTime).setMonth(nowTime.getMonth() - 6));
        startTime = this.$dayjs(
          new Date(temp.getFullYear() + "-" + (temp.getMonth() + 1)),
          "YYYY-MM"
        );
        xlist = new Array(6).fill(0).map((item, index) => ({
          time: this.$dayjs(
            new Date(startTime).setMonth(
              new Date(startTime).getMonth() + index
            ),
            "YYYY-MM"
          )
        }));
      }
      return {
        xlist,
        startTime,
        endTime
      };
    }

调用

const { xlist: arr } = this.fillDateTime(this.selectType);
        const xyList = arr.map(item => {
          item.totalMissionCount = 0;
          item.totalMissionFarmCount = 0;
          res.map(i => {
            if (i.time === item.time) {
              item.totalMissionCount = i.totalMissionCount;
              item.totalMissionFarmCount = i.totalMissionFarmCount;
            }
          });
          return item;
        });
        const xlist = xyList.map(item => item.time);
        var y1list = xyList.map(item => item.totalMissionCount);
        var y2list = xyList.map(item => item.totalMissionFarmCount);
        this.chartInstance.setOption({
          xAxis: {
            type: "category",
            data: xlist
          },
          series: [
            { name: "A项", type: "line", data: y1list },
            { name: "B项", type: "line", data: y2list }
          ]
        });