How to disable time from now with time picker antd

Viewed 480

I would like to know how I can disable the hour and minutes, taking into consideration from the current time and not from past hours.

enter image description here

  const disabledHours = () => {
    const hours = [];
    for (let i = 0; i < moment().hour(); i += 1) hours.push(i);
    return hours;
  };

  const disabledMinutes = (selectedHour) => {
    const minutes = [];
    if (selectedHour === moment().hour()) {
      for (let i = 0; i < moment().minute(); i += 1) minutes.push(i);
    }
    return minutes;
  };
   <TimePicker
       disabledHours={disabledHours}
       disabledMinutes={disabledMinutes}
       format="h:mm a"
       style={{ width: '100%' }}
       disabled={isLoading}
   />
1 Answers

If you want to disable future time:

const disabledHours = () => {
  const hours = [];
  const currentHour = moment().hour();

  for (let i = currentHour + 1; i <= 24; i++) {
    hours.push(i);
  }

  return hours;
};

const disabledMinutes = (selectedHour) => {
  const minutes = [];
  const currentMinute = moment().minute();
  if (selectedHour === moment().hour()) {
    for (let i = currentMinute; i <= 60; i++) {
      minutes.push(i);
    }
  }
  return minutes;
};

DEMO: https://codesandbox.io/s/antd-reproduction-template-forked-uslk0?file=/index.js

To avoid problems with switching AM or PM you can write any logic about how your want to set max time reference to onSelect callback, for example:

const TimeComponent = () => {
  const [selectedTime, setSelectedTime] = useState(moment());
  const disabledHours = () => {
    const hours = [];
    const currentHour = moment().hour();

    for (let i = currentHour + 1; i <= 24; i++) {
      hours.push(i);
    }

    return hours;
  };

  const disabledMinutes = (selectedHour) => {
    const minutes = [];
    const currentMinute = moment().minute();
    if (selectedHour === moment().hour()) {
      for (let i = currentMinute + 1; i <= 60; i++) {
        minutes.push(i);
      }
    }
    return minutes;
  };

  const onSelect = (time) => {
    if (time.isAfter(moment())) {
      console.log("ping");
      setSelectedTime(moment());
      return;
    }

    setSelectedTime(time);
  };

  return (
    <TimePicker
      onSelect={onSelect}
      disabledHours={disabledHours}
      disabledMinutes={disabledMinutes}
      format="h:mm a"
      value={selectedTime}
      style={{ width: "100%" }}
      use12Hours={true}
    />
  );
};
Related