vue利用elementUI組件實現日期時間選擇器帶快捷選項且自定義時間選擇

使用element日期時間選擇器帶快捷選項自定義時間:
需要picker-options
和格式化value-format

<el-form-item label="關閉時間:" prop="date">
          <el-date-picker
            v-model="date"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="開始日期"
            end-placeholder="結束日期"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </el-form-item>

首先定義想要的時間 formatDate是格式化時間的封裝,這個可以自己寫,不難,也可以自行百度!!

import { formatDate } from '@/utils/index'

// 獲取當前日期時間
const todayStart = formatDate(
  new Date(new Date()), // 當前時間
  'yyyy-MM-dd hh:mm:ss'
)

// 獲取15分鐘後的日期時間
const todayEnd = formatDate(
  new Date(new Date().getTime() + 1000 * 15 * 60), // 15分鐘後
  'yyyy-MM-dd hh:mm:ss'
)

實現快捷選擇日期時間 近15分鐘(後)/近1小時(後)/後一天的凌晨日期時間,三種快捷選項

pickerOptions: {
        shortcuts: [{
          text: '近15分鐘',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(end.getTime() + 1000 * 15 * 60)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '近1小時',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 1)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '今日',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(end.getTime() + 86400000 - (new Date().getHours() * 60 * 60 + new Date().getMinutes() * 60 + new Date().getSeconds()) * 1000)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      date: [todayStart, todayEnd]

下面是按當前時間往前推算的日期時間,分別有 近1小時/近3小時/今日凌晨/當前日期時間這幾種

const todayStart = formatDate(
  new Date(new Date().getTime() - 1 * 60 * 60 * 1000), // 近一小時
  'yyyy-MM-dd hh:mm:ss'
)
const todayTree = formatDate(
  new Date(new Date().getTime() - 3 * 60 * 60 * 1000), // 近三小時
  'yyyy-MM-dd hh:mm:ss'
)
const today = formatDate(
  new Date(new Date().setHours(0, 0, 0, 0)), // 今日凌晨
  'yyyy-MM-dd hh:mm:ss'
)
const todayEnd = formatDate(
  new Date(new Date()), // 當前時間
  'yyyy-MM-dd hh:mm:ss'
)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章