element-ui 周、月、季、年的日期时间选择器

日常做项目中经常会遇到根据周、月、季度、年的日期时间选择器,切换不同的时间时选择器也做出相对应的变化,并且获取相对的开始时间和结束时间。

效果如下:

1.先创建子组件--季度的日期选择器 

<template>
  <div class="time_quarter">
    <mark style="position:fixed;top:0;bottom:0;left:0;right:0;background:rgba(0,0,0,0);z-index:999;" v-show="showSeason"
      @click.stop="showSeason = false"></mark>
    <el-input placeholder="请选择季度" v-model="showValue" style="width:100%;" class="elWidth" @focus="showSeason = true">
      <i slot="prefix" class="el-input__icon el-icon-date"></i>
    </el-input>
    <el-card class="box-card" v-show="showSeason" style="width:100%">
      <div slot="header" class="clearfix" style="text-align:center;padding:0">
        <button type="button" aria-label="前一年"
          class="el-picker-panel__icon-btn el-date-picker__prev-btn el-icon-d-arrow-left" @click="prev"></button>
        <span role="button" class="el-date-picker__header-label">{{ year }}年</span>
        <button type="button" aria-label="后一年" @click="next" :class="{ notallow: year == limitTime }"
          class="el-picker-panel__icon-btn el-date-picker__next-btn el-icon-d-arrow-right"></button>
      </div>
      <div class="text item" style="text-align:center;">
        <el-button type="text" size="medium" style="width:40%;color: #606266;float:left;"
          @click="selectSeason(0)">第一季度</el-button>
        <el-button type="text" size="medium" style="float:right;width:40%;color: #606266;"
          @click="selectSeason(1)">第二季度</el-button>
      </div>
      <div class="text item" style="text-align:center;">
        <el-button type="text" size="medium" style="width:40%;color: #606266;float:left;"
          @click="selectSeason(2)">第三季度</el-button>
        <el-button type="text" size="medium" style="float:right;width:40%;color: #606266;"
          @click="selectSeason(3)">第四季度</el-button>
      </div>
    </el-card>
  </div>
</template>
<script>
export default {
  props: {
    valueArr: {
      default: () => {
        return ['01-03', '04-06', '07-09', '10-12'];
      },
      type: Array,
    },
    getValue: {
      default: () => { },
      type: Function,
    },
    // 传入显示的时间
    defaultValue: {
      default: "",
      type: String,
    },
    // 限制的时间
    limitTime: {
      type: String,
      default: "",
      require: true,
    },
  },
  data() {
    return {
      showSeason: false,
      season: "",
      year: new Date().getFullYear(),
      showValue: ''
    };
  },
  computed: {},
  created() {
    if (this.defaultValue) {
      let value = this.defaultValue;
      let arr = value.split("-");
      this.year = arr[0].slice(0, 4);

      var myseason = arr[1];
      this.showValue = `${this.year}年${this.whitchQuarter(myseason)}季度`;
    }
    console.log("whitchQuarter", this.whitchQuarter(10));
  },
  watch: {
    defaultValue: function (value, oldValue) {
      let arr = value.split("-");
      this.year = arr[0].slice(0, 4);
      var myseason = arr[1];
      this.showValue = `${this.year}年${this.whitchQuarter(myseason)}季度`;
    },
  },
  methods: {
    // 根据输入的月份判断是哪一个季节
    whitchQuarter(month) {
      let quarter = "";
      month = Number(month);
      switch (month) {
        case 1:
        case 2:
        case 3:
          quarter = "1";
          break;
        case 4:
        case 5:
        case 6:
          quarter = "2";
          break;
        case 7:
        case 8:
        case 9:
          quarter = "3";
          break;
        case 10:
        case 11:
        case 12:
          quarter = "4";
          break;
        default:
          console.error("The entered time is incorrect");
      }
      return quarter;
    },
    one() {
      this.showSeason = false;
    },
    prev() {
      this.year = this.year * 1 - 1;
    },
    next() {
      // 如果有时间限制的话会进行判断
      if (this.limitTime == "") {
        this.year = this.year * 1 + 1;
      } else if (this.limitTime != "" && this.year < this.limitTime) {
        this.year = this.year * 1 + 1;
      }
    },
    // 季度时间判定
    InitialTime(val) {
      let num = "";
      val = Number(val);
      switch (val) {
        case 1:
          num = "01";
          break;
        case 2:
          num = "04";
          break;
        case 3:
          num = "07";
          break;
        case 4:
          num = "10";
          break;
        default:
          console.error("时间格式有误!");
      }
      return num;
    },

    selectSeason(i) {
      let that = this;
      that.season = i + 1;
      let arr = that.valueArr[i].split("-");
      that.getValue(that.year + arr[0] + "-" + that.year + arr[1]);
      that.showSeason = false;
      this.showValue = `${this.year}年${this.season}季度`;
      var formatValue = `${this.year}-${this.InitialTime(this.season)}`;
      this.$emit("getTime", formatValue);
    }
  },
};
</script>
<style>
.notallow {
  cursor: not-allowed;
}
.time_box {
  position: relative;
}
.box-card {
  position: absolute;
  top: 40px;
  /* left: 22px; */
  padding: 0 3px 20px;
  z-index: 9999;
}
.time_quarter {
  width: 100%;

}
.time_quarter .el-input--small .el-input__inner {
  width: 82%;
}</style>

2.父组件

 2.1父组件--html

 2.2父组件--js

以下是日期选择器切换时的时间换算

//获取周的开始时间和结束时间
        getMonday(type, dates) {
            var now = new Date();
            var nowTime = now.getTime();
            var day = now.getDay();
            var longTime = 24 * 60 * 60 * 1000;
            var n = longTime * 7 * (dates || 0);
            if (type == "s") {
                var dd = nowTime - (day - 1) * longTime + n;
            };
            if (type == "e") {
                var dd = nowTime + (7 - day) * longTime + n;
            };
            dd = new Date(dd);
            var y = dd.getFullYear();
            var m = dd.getMonth() + 1;
            var d = dd.getDate();
            m = m < 10 ? "0" + m : m;
            d = d < 10 ? "0" + d : d;
            var day = y + "-" + m + "-" + d;
            return day;
        },
        //周
        changeTime(data) {
            let date = new Date(data);
            let y = date.getFullYear();
            let m = date.getMonth();
            let d = date.getDate();
            let week = date.getDay();
            let start = new Date(y, m, d - week + 1);
            let end = new Date(y, m, d - week + 7);
            this.queryParams.startTime = this.getCurrentTime(start, 0) + " 00:00:00";
            this.queryParams.endTime = this.getCurrentTime(end, 0) + " 23:59:59";
        },
        //月
        changeTimeM(data) {
            this.queryParams.startTime = this.getCurrentTime(data, 0) + " 00:00:00";
            this.queryParams.endTime = this.getCurrentTime(this.getCuurrentTimeM(data), 0) + " 23:59:59";
            console.log(this.queryParams)
        },
        //年
        changeTimeY(data) {
            this.queryParams.startTime = this.getCurrentTime(data, 0) + " 00:00:00";
            this.queryParams.endTime = this.getCurrentTime(this.getCuurrentTimeY(data), 0) + " 23:59:59";
            console.log(this.queryParams)
        },
        getCurrentTime(data, num) {
            let date = new Date(data)
            let Y = date.getFullYear()
            let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)
            let D = date.getDate() + num < 10 ? ('0' + (date.getDate() + num)) : (date.getDate() + num);
            date = Y + '-' + M + '-' + D;
            return date
        },
        getCuurrentTimeM(data) {
            let date = new Date(data)
            let Y = date.getFullYear();
            let M = date.getMonth();
            return new Date(Y, M + 1, 0).toLocaleDateString();
        },
        getCuurrentTimeY(data) {
            let date = new Date(data)
            let Y = date.getFullYear();
            return new Date(Y, 11, 31).toLocaleDateString();
        },
        //获得某月的天数
        getMonthDays: function (nowYear, myMonth) {
            var monthStartDate = new Date(nowYear, myMonth, 1);
            var monthEndDate = new Date(nowYear, myMonth + 1, 1);
            var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
            return days;
        },
        //获得本季度的结束日期
        getQuarterEndDate(data) {
            let date = new Date(data);
            let nowYear = date.getFullYear();
            let M = date.getMonth();
            var quarterEndMonth = M + 2;
            var quarterStartDate = new Date(nowYear, quarterEndMonth, this.getMonthDays(nowYear, quarterEndMonth));
            return this.getAllDate(quarterStartDate, "yyyy-MM-dd");
        },
        //获得本季度的开始月份
        getQuarterStartMonth: function (nowMonth) {
            var quarterStartMonth = 0;
            if (nowMonth < 3) {
                quarterStartMonth = 0;
            }
            if (2 < nowMonth && nowMonth < 6) {
                quarterStartMonth = 3;
            }
            if (5 < nowMonth && nowMonth < 9) {
                quarterStartMonth = 6;
            }
            if (nowMonth > 8) {
                quarterStartMonth = 9;
            }
            return quarterStartMonth;
        },
        //获得日期
        getAllDate: function (date, fmt) {
            if (null == fmt || undefined == fmt || "" == fmt)
                fmt = "yyyy/MM/dd";
            var date = new Date(date);
            var o = {
                "M+": date.getMonth() + 1, //月份
                "d+": date.getDate(), //日
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt))
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        },
        getmgTime(data) {
            let start = data + "-01";
            this.queryParams.startTime = start + " 00:00:00";
            let end = this.getQuarterEndDate(start);
            this.queryParams.endTime = end + " 23:59:59";
        },
        watch: {
            //监听内容
            timeType() {
                if (this.timeType == 1) {//周
                    this.value2 = new Date(new Date().valueOf());
                    this.queryParams.startTime = this.getMonday("s", 0) + " 00:00:00";
                    this.queryParams.endTime = this.getMonday("e", 0) + " 23:59:59";
                } else if (this.timeType == 2) {//月
                    this.value2 = new Date().getFullYear() + '-' + (new Date().getMonth() + 1);
                    this.changeTimeM(this.value2);
                } else if (this.timeType == 3) {//季度
                    let date = new Date();
                    let y = date.getFullYear();
                    let M = date.getMonth();
                    let quarterStartDate = new Date(y, this.getQuarterStartMonth(M), 1);
                    let starts = this.getAllDate(quarterStartDate, "yyyy-MM-dd");
                    let end = this.getQuarterEndDate(starts);
                    this.queryParams.startTime = starts + " 00:00:00";
                    this.queryParams.endTime = end + " 23:59:59";
                } else if (this.timeType == 4) {//年
                    let date = new Date();
                    let y = date.getFullYear();
                    this.value2 = y.toString();
                    this.changeTimeY(this.value2);
                }
            }
        },

    

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值