项目背景
公司需求,用户选择时间时,不可选择当前时间之前的时间(包含时分秒), 如果不选择当天,时分秒则不禁用,可自由选择。
技术
vue3 + element plus
项目展示
html展示
<el-date-picker
v-model="dateTimeRange"
type="datetimerange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
placeholder="选择日期时间"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
:default-time="defaultTime"
:disabledDate="disabledDateFn"
@update:modelValue="handleDateChange"
@calendar-change="onChangePanel"
:disabled-hours="disabledHours"
:disabled-minutes="disabledMinutes"
:disabled-seconds="disabledSeconds"
:style="{
height: '30px',
maxHeight: '30px',
}"
/>
js展示
禁用当天之前的日期
// 禁用比当前时间小的日期
const disabledDateFn = (time: any) => {
//比当前时间小的日期禁用(返回false则禁用)
return time.getTime() < Date.now() - 24 * 3600 * 1000;
};
将当前时间和时间选择框的选择做对比,如果选择时间超出-解除时分秒禁用
// 获取时间选择框选中的时间值
const onChangePanel = (time) => {
console.log('time', time);
// 将选中的第一个时间转为年月日 时分秒 -> 现在是转为了时间戳
const firstDate = transNowDate(time[0]);
// 获取当前时间戳 -> 将时间选择器选择的第一个时间和当前时间戳做对比,如果选中的时间超出当前时间,不禁用时分秒
const now = new Date();
// 获取当前时间的时间戳(毫秒)
const timestamp = now.getTime();
if (firstDate > timestamp) {
beyondCurrentTime.value = true;
} else {
beyondCurrentTime.value = false;
}
console.log('选中的时间', firstDate, timestamp);
};
禁用时分秒
// beyondCurrentTime.value 当前时间和选择框的时间比对,不是当天时:值为true,时分秒可以自由选择;值为false,当前之前的时分秒禁用
const disabledHours = (type) => {
if (type === 'start' && !beyondCurrentTime.value) {
const Hours: number[] = [];
if (new Date(selectTimes.value).getTime() > Date.now()) return a;
for (let i = 0; i < 24; i++) {
if (new Date().getHours() <= i) continue;
Hours.push(i);
}
return Hours;
}
};