1. 程式人生 > 其它 >antd(vue)日期選擇器日期控制問題--範圍時間選不到最後一天

antd(vue)日期選擇器日期控制問題--範圍時間選不到最後一天

技術標籤:antdvantdvue日期選擇器rangePicker

需求是:後端返回一個時間段,需要限制只能選擇在時間段內的時間,可以選擇返回的開始日期和結束日期
比如: 返回的時間是2021/02/03-2021/02/27,可以選擇他們之間的時間、2021/02/03和2021/02/27的時間
部分程式碼如下:

     <template slot-scope="text, record">
       <a-range-picker
         v-if="record.cate"
         v-model="record.sprintDate"
:disabled-date="(current) => disabledDate(record, current)" // 選擇日期控制 :shoe-today="false" style="width: 220px" format="YYYY/MM/DD" value-format="YYYY/MM/DD" @change="(date) => handleStartDate(record, date)"
/> </template> // 限制日期不讓選的方法 disabledDate(record, current) { // this.currentExpandRow 後端返回時間 const startDate = this.currentExpandRow.startDate || '' const endDate = this.currentExpandRow.endDate || '' return ( (current && current < moment
(startDate)) || current > moment(endDate) ) },

但是發現27號被禁用了
在這裡插入圖片描述
原因: antd使用的是moment庫
當宣告 moment 物件的時候,如果只宣告日期,沒有宣告時間,時間就是當前時間(日期當然是宣告的日期)。
而當前時間一定是在今天之內的,也就是說當判斷的時候,當前時間點可能會大於臨界值,所以最後一天就不能選擇了。
解決: 這時候就需要用到endOf()方法

endOf() 通過將原始的 moment 設定為時間單位的末尾來對其進行更改。

比如:
moment().endOf(“year”) // 將 moment 設定為今年的 12 月 31 日 23:59:59.999
這時候我們就需要新增moment().endOf(“day”),就是設定為當天的23:59:59.999
程式碼如下

    disabledDate(record, current) {
    // this.currentExpandRow 後端返回時間
      const startDate = this.currentExpandRow.startDate || ''
      const endDate = this.currentExpandRow.endDate || ''
      return (
        (current && current < moment(startDate)) ||
        current > moment(endDate).endOf('day')
      )
    },

在這裡插入圖片描述