Element UI 日期组件(el-date-picker)控制选择过去或未来日期范围

704 阅读1分钟

一、过去多少月以内的日期范围

  • 例如:过去12月以内
<template>
  <div>
    <el-date-picker
      v-model="date"
      :picker-options="pickerOptions"
      type="datetime"
      placeholder="选择日期和时间"
    ></el-date-picker>
  </div>
</template>

<script>
export default {
  data() {
    return {
      date: null,
      pickerOptions: {
        disabledDate(time) {
          const currentDate = new Date() // 获取当前日期
          const dateBeforeTwelveMonths = new Date() // 获取12个月之前的日期
          dateBeforeTwelveMonths.setMonth(
            dateBeforeTwelveMonths.getMonth() - 12
          )

          return (
            time.getTime() < dateBeforeTwelveMonths.getTime() ||
            time.getTime() > currentDate.getTime()
          )
        },
      },
    }
  },
}
</script>

一、未来多少月以内的日期范围

  • 例如:从现在起未来12个月的日期
<template>
  <div>
    <el-date-picker
      v-model="date"
      :picker-options="pickerOptions"
      type="date"
      placeholder="选择日期"
    ></el-date-picker>
  </div>
</template>

<script>
export default {
  data() {
    return {
      date: null,
      pickerOptions: {
        disabledDate(time) {
          // 获取当前日期和12个月之前的日期
          const currentDate = new Date()
          const dateBeforeTwelveMonths = new Date()
          dateBeforeTwelveMonths.setMonth(
            dateBeforeTwelveMonths.getMonth() + 12
          )

          // 将时间戳转化为日期格式
          const start = new Date(
            currentDate.getFullYear(),
            currentDate.getMonth(),
            currentDate.getDate()
          )
          const end = new Date(
            dateBeforeTwelveMonths.getFullYear(),
            dateBeforeTwelveMonths.getMonth(),
            dateBeforeTwelveMonths.getDate()
          )

          // 判断当前日期是否在12个月之前的范围内
          return (
            time.getTime() < start.getTime() || time.getTime() > end.getTime()
          )
        },
      },
    }
  },
}
</script>