antd DatePicker日期控件設置禁用時間范圍


我們知道antd官網不可選時間使用的是 RangePicker 如下圖:

 

 


但有時候我們需要使用 DatePicker 單獨設置起始時間,如圖:

 

 

廢話不多說,直接上代碼:(這里用的是react+ts+antd)

const dateFormat = 'YYYY-MM-DD HH:mm:ss';
function DateInfo() {
    const [startTime, setStartTime] = useState<moment>(null);
    const [endTime, setEndTime] = useState<moment>(null);

    // 禁用開始時間(開始時間不能大於當前時間)
    function disabledStartDate(startValue) {
        if (!startValue || !endTime) {
            return startValue <= moment().startOf('days');
        }
        return startValue <= moment().startOf('days') || startValue.valueOf() > endTime.valueOf();
    }

    // 禁用結束時間
    const disabledEndDate = (endValue) => {
        if (!endValue || !startTime) {
            return false;
        }
        return endValue.valueOf() <= startTime.valueOf();
    };
    return (
          <Row>
            <Col span={9}>
                <Form.Item
                    label="起始時間"
                    name="effectTime"
                    rules={[{ required: true, message: '請選擇起始時間' }]}
                >
                    <DatePicker
                        format={dateFormat}
                        disabledDate={disabledStartDate}
                        onChange={(value) => setStartTime(value)}
                        showTime
                    />
                </Form.Item>
            </Col>
            <Col span={9}>
                <Form.Item
                    label="失效時間"
                    name="expireTime"
                    rules={[{ required: true, message: '請選擇失效時間' }]}
                >
                    <DatePicker
                        format={dateFormat}
                        disabled={!startTime}
                        disabledDate={disabledEndDate}
                        onChange={(value) => setEndTime(value)}
                        showTime
                    />
                </Form.Item>
            </Col>
        </Row>
      )
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM