Search code examples
reactjsdatepickerantd

how to disable all the Sundays and array of specific days in ant design date picker


following code disabled all the previous dates including today, but I want to disable all the Sundays and array of specific days in ant design date picker.

< DatePicker size = "large"
  format = "DD/MM/YYYY"
  nChange = {
    this.onDate1Change
  }
  disabledDate = {
    current => {
      return current && current < moment().endOf('day');
    }
  }
/>


Solution

  • To start we have a look at antd's Datepicker example in the depending docs.

    1. Disable all Sundays

    We use the moment.js lib to check the days and disable all sundays (here it is the first == zero).

    E.g.:

    function disabledDate(current) {
      // Can not select sundays and predfined days
      return moment(current).day() === 0 
    }
    
    1. Disable specific days

    First we define an array of our dates and then check if a converted day is in our disabled array.

    const disabledDates = ["2020-07-21", "2020-07-23"];
    
    function disabledDate(current) {
      // Can not select Sundays and predefined days
      return disabledDates.find(date => date === moment(current).format("YYYY-MM-DD"));
    }
    
    1. Putting all together

    Now we can combine both solutions. A working example can be found in this CodeSandbox.

    E.g.:

    import React from "react";
    import ReactDOM from "react-dom";
    import "antd/dist/antd.css";
    import "./index.css";
    import moment from "moment";
    import { DatePicker } from "antd";
    
    const disabledDates = ["2020-07-21", "2020-07-23"];
    
    function disabledDate(current) {
      // Can not select Sundays and predefined days
      return (
        moment(current).day() === 0 ||
        disabledDates.find(date => date === moment(current).format("YYYY-MM-DD"))
      );
    }
    
    ReactDOM.render(
      <>
        <DatePicker
          format="YYYY-MM-DD HH:mm:ss"
          disabledDate={disabledDate}
          showTime={{ defaultValue: moment("00:00:00", "HH:mm:ss") }}
        />
      </>,
      document.getElementById("container")
    );