一个基于vue3+javascript+elementPlus+dayjs 实现 日期时间选择器(datetime)并禁用未来时间(到时分秒)

一个基于vue3+javascript+elementPlus+dayjs 实现 日期时间选择器(datetime)并禁用未来时间(到时分秒)

一定要注意elementPlus版本问题 ,十分重要!!!
本地版本是"element-plus": “^2.10.3”
拆箱即用版 话不多说,直接上代码


<template>
  <div class="block">
    <span class="demonstration">日期时间-type:datetime 禁止选择未来时间</span>
    {{ value1 }}
    <el-date-picker
      v-model="value1"
      type="datetime"
      :disabled-date="disabledDate"
      :disabled-hours="disabledHours"
      :disabled-minutes="disabledMinutes"
      :disabled-seconds="disabledSeconds"
      placeholder="Select date and time"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import dayjs from "dayjs";
const value1 = ref("");
console.log("value1::", value1);
let currentDateTime = dayjs();
// 禁止选择未来日期
const disabledDate = (time) => {
  return dayjs(time).isAfter(dayjs().endOf("day"));
};
// 禁止选择未来小时
const disabledHours = (role, date) => {
  if (!date) return [];
  if (dayjs(date).isSame(dayjs(), "day")) {
    // console.log("是同一天,禁用未来小时");
    const currentHour = dayjs().hour();
    return Array.from(
      { length: 23 - currentHour },
      (_, i) => currentHour + 1 + i
    );
  }
  return [];
};
// 禁用未来的分钟
const disabledMinutes = (selectedHour, role, date) => {
  if (!date) return [];

  // 只有选择今天且选择当前小时时,才需要禁用未来的分钟
  if (
    dayjs(date).isSame(currentDateTime, "day") &&
    selectedHour === currentDateTime.hour()
  ) {
    const currentMinute = currentDateTime.minute();
    return Array.from(
      { length: 59 - currentMinute },
      (_, i) => currentMinute + 1 + i
    );
  }

  return [];
};
// 禁用未来的秒数
const disabledSeconds = (selectedHour, selectedMinute, role, date) => {
  if (!date) return [];

  // 只有选择今天、当前小时且当前分钟时,才需要禁用未来的秒数
  if (
    dayjs(date).isSame(currentDateTime, "day") &&
    selectedHour === currentDateTime.hour() &&
    selectedMinute === currentDateTime.minute()
  ) {
    const currentSecond = currentDateTime.second();
    return Array.from(
      { length: 59 - currentSecond },
      (_, i) => currentSecond + 1 + i
    );
  }

  return [];
};
// range:[ "2025-09-10T16:00:00.000Z", "2025-10-14T16:00:00.000Z" ]
// datetime: Mon Sep 01 2025 00:00:00 GMT+0800 (中国标准时间)
</script>

<style scoped>
.block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值