。
涉及到的知識點:獲取某一天的0點和23:59:59
廢話不多說,上代碼:
<template>
<div>
<el-date-picker
v-model="timeValue"
type="datetimerange"
:picker-options="pickerOptions"
:default-time="defaultTime"
range-separator="至"
start-placeholder="開始日期"
end-placeholder="結束日期"
:value-format="valueFormat"
:format="format"
popper-class="cusDatetimer"
align="right">
</el-date-picker>
</div>
</template>
<script>
export default {
data(){
return {
timeValue:[],//綁定時間的值
defaultTime:['00:00:00', '23:59:59'],//選擇日期后的默認時間
valueFormat:"yyyy-MM-dd HH:mm:ss",//綁定值的格式
format:"yyyy/MM/dd HH:mm:ss",//日期顯示格式
pickerOptions:{//配置項
shortcuts: [{//設置快件選項
text: "最近7天",
onClick: picker => {
const end = new Date();
const start = this.getBeforeDate(new Date(), 6);
picker.$emit("pick", [start, end]);
}
},
{
text: "最近30天",
onClick: picker => {
const end = new Date();
const start = this.getBeforeDate(new Date(), 30);
picker.$emit("pick", [start, end]);
}
},
{
text: "最近90天",
onClick: picker => {
const end = new Date();
const start = this.getBeforeDate(new Date(), 90);
picker.$emit("pick", [start, end]);
}
}
],
// 監聽每一次選擇日期的事件
onPick: ({ maxDate, minDate }) => {//最大時間 最小時間
this.choiceDate = minDate.getTime();//當選一個日期時 就是最小日期
// // 如何你選擇了兩個日期了,就把那個變量置空
if (maxDate) this.choiceDate = ''
},
// 設置禁用狀態 time是日歷上的每一個時間
disabledDate: time => {
// 如何選擇了一個日期
if (this.choiceDate) {
// 7天的時間戳
const one = 6 * 24 * 3600 * 1000;//這里如果乘以7相當於限制8天以內的 所以乘以6
// 當前日期 - one = 7天之前
const minTime = this.choiceDate - one;
// 當前日期 + one = 7天之后
const maxTime = this.choiceDate + one;
return (
time.getTime() < minTime ||
time.getTime() > maxTime ||
// 限制不能選擇今天及以后
time.getTime() > this.getDayStartOrEnd(new Date(),"end")
)
} else {
// 如果沒有選擇日期,就要限制不能選擇今天及以后
return time.getTime() > this.getDayStartOrEnd(new Date(),"end");
}
}
}
}
},
methods:{
//返回幾天前的毫秒數
getBeforeDate(date = new Date(), days = 7) {
date.setTime(date.getTime() - 3600 * 1000 * 24 * days);
return date;
},
// 獲取當天0點或23:59:59
getDayStartOrEnd(time,type = "start"){//end 返回毫秒數
if(type == "start"){
return new Date(time).setHours(0,0,0,0);//hourse、min、sec、millisec
}else{
return new Date(time).setHours(23,59,59,999);
}
}
}
}
</script>
<style lang="scss">
</style>
。
