Newer
Older
KaiFengPC / src / mixins / timeSelect.js
@zhangdeliang zhangdeliang on 23 May 2 KB 初始化项目
export const timeSelect = {
  setup() {
    function timestampToTime(timestamp) {
      var date = new Date(timestamp); // 时间戳为10位需*1000,时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D = date.getDate() + " ";
      return Y + M + D;
    }

    // 周选择器开始时间和结束时间
    function formatWeekTime(val) {
      if (val == "") {
        queryParams.value.datetime = [];
        queryParams.value.weekStartDate = "";
        queryParams.value.WeekEndDate = "";
        return;
      }
      let todayDay = val ? new Date(val) : new Date();
      console.log(todayDay);
      let todayOfWeek = todayDay.getDay();
      console.log(todayOfWeek);
      let spendDay = 1;
      if (todayOfWeek !== 0) {
        spendDay = 7 - todayOfWeek; // 开始时间到结束时间还有几天
      }
      //  86400000为一天的毫秒数
      let startTimeNum = todayDay.valueOf() - (6 - spendDay) * 86400000; // 开始时间时间戳
      let endTimeNum = todayDay.valueOf() + spendDay * 86400000; // 结束时间时间戳
      let startTimeStr = timestampToTime(startTimeNum); // 时间戳转字符串
      let endTimeStr = timestampToTime(endTimeNum);
      let startDate = proxy
        .moment(startTimeStr)
        .add(5, "days")
        .format("YYYY-MM-DD");
      let endDate = proxy
        .moment(endTimeStr)
        .add(5, "days")
        .format("YYYY-MM-DD");
      queryParams.value.weekStartDate = startDate;
      queryParams.value.WeekEndDate = endDate;
      queryParams.value.datetime = [startDate, endDate];
    }
    //选择周
    function changeWeek() {
      queryParams.value.monthTime = queryParams.value.yearTime = "";
      formatWeekTime(queryParams.value.weekTime);
    }
    //选择月
    function changeMonth() {
      queryParams.value.weekTime = queryParams.value.yearTime = "";
      formatWeekTime(queryParams.value.weekTime);
      queryParams.value.datetime = [
        proxy
          .moment(queryParams.value.monthTime)
          .startOf("months")
          .format("YYYY-MM-DD"),
        proxy
          .moment(queryParams.value.monthTime)
          .endOf("months")
          .format("YYYY-MM-DD"),
      ];
    }
    //选择年
    function changeYear() {
      queryParams.value.monthTime = queryParams.value.weekTime = "";
      changeweek(queryParams.value.weekTime);
      queryParams.value.datetime = [
        proxy
          .moment(queryParams.value.yearTime)
          .startOf("years")
          .format("YYYY-MM-DD"),
        proxy
          .moment(queryParams.value.yearTime)
          .endOf("years")
          .format("YYYY-MM-DD"),
      ];
    }
    // 暴露出去
    return {
      changeWeek,
      changeMonth,
      changeYear,
    };
  },
};