// 不可选日期时间
const disabledDate = (time: Date) => {
return time.getTime() < Date.now() - 8.64e7;
};
const selectedTimeRange = ref({ start: null, end: null }); // 用于存储开始和结束时间
const handleCalendarChange = (val: [Date, null | Date]) => {
selectedTimeRange.value = {
start: val[0],
end: val[1]
};
};
const disabledHours = (type: string) => {
const now = new Date();
if (!selectedTimeRange.value.start && !selectedTimeRange.value.end) {
// 如果尚未选择任何时间,返回空数组
return [];
}
const selectedDate = type === 'start' ? selectedTimeRange.value.start : selectedTimeRange.value.end;
if (selectedDate) {
const selectedDay = selectedDate.getDate();
const currentDay = now.getDate();
// 如果选择的是今天,则禁用当前小时之前的小时
if (selectedDay === currentDay) {
return Array.from({ length: now.getHours() }, (_, i) => i);
}
}
return [];
};
const disabledMinutes = (hour: number, type: string) => {
const now = new Date();
const selectedDate = type === 'start' ? selectedTimeRange.value.start : selectedTimeRange.value.end;
if (selectedDate) {
const selectedDateTime = new Date(selectedDate);
const isToday = selectedDateTime.getDate() === now.getDate();
const isCurrentHour = hour === now.getHours();
// 如果选择的日期是今天,且小时是当前小时,禁用当前分钟之前的分钟
if (isToday && isCurrentHour) {
return Array.from({ length: now.getMinutes() }, (_, i) => i);
}
}
return [];
};
const disabledSeconds = (hour: number, minute: number, type: string) => {
const now = new Date();
const selectedDate = type === 'start' ? selectedTimeRange.value.start : selectedTimeRange.value.end;
if (selectedDate) {
const selectedDateTime = new Date(selectedDate);
const isToday = selectedDateTime.getDate() === now.getDate();
const isCurrentHour = hour === now.getHours();
const isCurrentMinute = minute === now.getMinutes();
// 如果选择的日期、小时和分钟是当前时间,则禁用当前秒之前的秒
if (isToday && isCurrentHour && isCurrentMinute) {
return Array.from({ length: now.getSeconds() }, (_, i) => i);
}
}
return [];
};
<el-date-picker
v-model="disposableDateTime"
type="datetimerange"
range-separator="至"
:disabled-hours="disabledHours"
:disabled-minutes="disabledMinutes"
:disabled-seconds="disabledSeconds"
value-format="YYYY-MM-DD HH:mm:ss"
start-placeholder="开始日期"
end-placeholder="结束日期"
@calendar-change="handleCalendarChange"
:disabled-date="disabledDate"
/>
el-date-picker的type设为datetimerange,即日期时间段,限制到时分秒
于 2024-09-09 15:33:36 首次发布