Antd--DatePicker常用设置可选、禁选日期时间范围

import moment, { Moment } from 'moment'
import { DatePicker } from 'antd'

const [dates, setDates] = useStaten<[Moment, Moment] | null>(null)

<DatePicker.RangePicker
    onCalendarChange={val => setDates(val)}
    disabledDate={disabledDate}
    value={dates} 
/>

1、设置可选范围

const disabledDate = (current: Moment): boolean => {
    if (!dates || dates.length === 0) {
      return false;
    }

    // .diff
    const tooLate = dates[0] && current.diff(dates[0], 'days') > 20;
    const tooEarly = dates[1] && dates[1].diff(current, 'days') > 20;
    return tooEarly || tooLate;
}

moment(endDate).diff(moment(startDate), 'seconds' /  'minutes' / 'hours' /  'days' / 'months'  /  'years') 

2、早于某一日期

const disabledDate = (current: Moment): boolean => {
     return current && current.isBefore(moment().subtract(3, 'months'))
}

     currentDate.isBefore(moment().subtract(Number, string))

     早于当前时间

function range (start, end) {
    const result = []
    for (let i = start; i < end; i++) {
        result.push(i)
    }
    return result
}


function disabledRangeTime(time: any, type: string): unknown {
    if (type === 'start') {
        const hours = moment().hours()
        const minute = moment().minute()
        if (moment().date() === moment(time).date()) {
            return {
                disabledHours: () => range(0, 24).splice(0, hours),
                disabledMinutes: () => moment(time).hours() === hours 
                    ? range(0, minute) : range(0, 0)
            }
        }
    }
    return {
        disabledHours: () => range(0, 0),
        disabledMinutes: () => range(0, 0)
    }
}


版权声明:本文为weixin_41695981原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。