<template>
<div>
<el-date-picker
ref="datePickerRef"
v-model="val"
:minute-step="5"
type="datetimerange"
class="app-sys-date-picker"
:format="TIME_FORMAT"
:value-format="TIME_FORMAT"
:teleported="false"
:disabled-date="getDisabledDate"
:disabled-minutes="getDisabledMinutes"
:disabled-hours="getDisabledHours"
@change="onSelectTimePicker"
@calendar-change="getOtherEndTime"
/>
</div>
</template>
<script setup lang="ts">
import dayjs, { type UnitTypeShort } from 'dayjs';
const TIME_FORMAT = 'YYYY/MM/DD HH:mm';
const endTime = ref<string>('')
//获取到面板上选择的结束时间日期
const getOtherEndTime = (val) => {
const endTimeFormat = val[1] ? dayjs(val[1]).format(TIME_FORMAT) : '';
endTime.value = endTimeFormat;
};
//限制日期的选择,只能选择近三天
const getDisabledDate = (date) => {
const d = dayjs(date).valueOf();
const end = dayjs().valueOf();
const start = dayjs().add(-3, 'day').valueOf();
return d > end || d < start;
};
//限制时分的公共办法,只能选择当前时间之前
const restrictionsHMPublic = (type: boolean, selectHours?: number) => {
const disableArrays: number[] = [];
const now = dayjs();
const nowHours = now.get('hour');
const nowMinutes = now.get('minute');
const TIME_FORMAT = 'YYYY-MM-DD';
const nowDay = now.format(TIME_FORMAT);
if (!endTime.value) endTime.value = nowDay;
const selectedDay = dayjs(endTime.value).format(TIME_FORMAT);
if (selectedDay !== nowDay || (type && nowHours !== selectHours)) return disableArrays;
for (let i = 0; i < 60; i++) {
const getCompareTime = type ? nowMinutes : nowHours;
if (type && getCompareTime >= i && i % 5 === 0) continue;
if (!type && getCompareTime >= i) continue;
disableArrays.push(i);
}
return disableArrays;
};
const getDisabledHours = () => {
const hoursDisableArrays: any = restrictionsHMPublic(false);
return hoursDisableArrays;
};
const getDisabledMinutes = (selectHour) => {
let minutesDisableArrays: any = restrictionsHMPublic(true, selectHour);
//其余的日期的分钟只能取五的倍数
if (minutesDisableArrays.length === 0) {
const allMinutes = Array.from({ length: 59 }, (_, i) => i + 1);
minutesDisableArrays = allMinutes.filter((i) => i % 5 !== 0);
}
return minutesDisableArrays;
};
//扩展-选择当前时间最接近5的倍数的分钟的往前5分钟
const getDefaultTimePeriod = () => {
const period = '5-m'
const [num, type] = period ? period.split('-') : [];
const minuteRemainder = +dayjs().minute() % 5;
const end = dayjs()
.add(-+minuteRemainder, 'm' as UnitTypeShort)
.format(TIME_FORMAT);
const start = dayjs(end)
.add(-+num, type as UnitTypeShort)
.format(TIME_FORMAT);
const timePeriod = [start, end];
console.log(timePeriod)
};
</script>