简体   繁体   中英

How to properly disable time in ant design for a datapicker?

The problem is that the date disable works correctly, but if you set a time limit, it crashes, if I choose a time before 12:00, the time is disabled correctly, but if after 12:00 then the ant is disabled all day

Here is my code

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import moment from "moment";
import { DatePicker, Space } from "antd";

function disabledDate(current) {
  return current.isSameOrBefore("2021-04-17 17:00"); //work incorrect 
  return current.isSameOrBefore("2021-04-17 03:00"); //work correct
}                                      

const onChangeInner = (value,dateToString) => {
  console.log(dateToString)
};

ReactDOM.render(
  <Space direction="vertical" size={12}>
    <DatePicker
      onChange={onChangeInner}
      format="YYYY-MM-DD HH:mm"
      disabledDate={disabledDate}
      showTime={{ defaultValue: moment("00:00", "HH:mm") }}
    />
  </Space>,
  document.getElementById("container")
);

Link to codesandbox

so I edit my code and now it looks loke this but there is stil one problem even when user dont choose hours it can be less than I need and button ok still enabled, how fix this problem

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import moment from "moment";
import { DatePicker, Space } from "antd";

const App = () => {
  const [startTime, setStartTime] = useState("");

  const onChange = (value, string) => {
    setStartTime(string);
  };

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

  function disabledDateEndPicker(current) {
    if (!startTime) return true;
    return current && current < moment(startTime, "YYYY-MM-DD");
  }

  function disabledDateTimeEndPicker(current) {

    let currentD = moment(current).format("YYYY-MM-DD");
    let start = moment(startTime).format("YYYY-MM-DD");
    let test = new Date(currentD) - new Date(start);
    if (test === 0) {
      let hoursDisable = +moment(startTime).format("HH");

      let minutesDisable = 0;

      if (hoursDisable >= moment(current).format("HH")) {
        minutesDisable = +moment(startTime).format("mm");
      }

      return {
        disabledHours: () => range(0, 24).splice(0, hoursDisable), 
        disabledMinutes: () => range(0, minutesDisable)
      };
    }
  }



  return (
    <Space direction="vertical" size={12}>
      <DatePicker
        showNow={false}
        onChange={onChange}
        format="YYYY-MM-DD HH:mm"
        showTime={{ defaultValue: moment("00:00", "HH:mm") }}
      />
      <DatePicker
        showNow={false}
        disabledDate={disabledDateEndPicker}
        format="YYYY-MM-DD HH:mm"
        disabledTime={disabledDateTimeEndPicker}
        showTime={{ defaultValue: moment("00:00", "HH:mm") }}
      />
    </Space>
  );
};

const rootElement = document.getElementById("container");
ReactDOM.render(<App />, rootElement);

https://codesandbox.io/s/loving-knuth-0ypjy?file=/index.js:0-2045

Time limitation cannot be set like that. You have to provide an additional function as prop to DatePicker named disabledTime .

In your case you can do something like the following:

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

function disabledDate(current) {
  return current && current.isSameOrBefore("2021-04-17");
}

function disabledTime(current) {
  if (current && current.format("YYYY-MM-DD") === "2021-04-17") {
    return {
      disabledHours: () => range(0, 17),
      // disabledMinutes: () => range(30, 60), use this if you need to limit minutes too
    };
  }
}

const onChangeInner = (value) => { ... };

ReactDOM.render(
  ...
    <DatePicker
      onChange={onChangeInner}
      format="YYYY-MM-DD HH:mm"
      disabledDate={disabledDate}
      disabledTime={disabledTime}
      showTime={{ defaultValue: moment("00:00", "HH:mm") }}
    />
  ...
);

  export function DateAndTime() { 
  // this example is to disable date and time divided into two parts:
  // the first is for disabling specific days.
  // the second is for disabling specific minutes in chosen hours of specific days. 
  // I browsed only minutes 0, 15, 30, and 45 using the minuteStep property,

          const [currentDateTime, setCurrentDateTime] = useState();
          const [currentHour, setCurrentHour] = useState();
        
          const changeSelection = (date) => {
            if (date) {
              setCurrentDateTime(date._d);
              console.log("Date: ", date._d.getHours());
              setCurrentHour(date._d.getHours());
            } else {
              console.log("Clear");
            }
          };
          const disabledDates = ["2022-11-21", "2022-11-23"];
        
          function disabledDate(current) {
            // Can not select Sundays and predefined days
            return (
              current.valueOf() < Date.now() ||
              moment(current).day() === 0 ||
              disabledDates.find(
                (date) => date === moment(c`enter code here`urrent).format("YYYY-MM-DD")
              )
            );
          }
        
          const disabledDaysArr = [
            {`enter code here`
              day: "2022-11-25",
              hours: [
                { hour: 11, minutes: [45] },
                { hour: 13, minutes: [0, 15] },
              ],
            },
            {
              day: "2022-11-28",
              hours: [
                { hour: 12, minutes: [30] },
                { hour: 14, minutes: [0, 45] },
              ],
            },
          ];
          
          function disabledTimes() {
            if (disabledDaysArr) {
              for (let i = 0; i < disabledDaysArr.length; i++) {
                if (
                  moment(currentDateTime).format("YYYY-MM-DD") == disabledDaysArr[i].day
                ) {
                  for (let j = 0; j < disabledDaysArr[i].hours.length; j++) {
                    console.log("here: ", disabledDaysArr[i].hours[j].hour);
                    if (currentHour == disabledDaysArr[i].hours[j].hour) {
                      return disabledDaysArr[i].hours[j].minutes;
                    }
                  }
                }
              }
            }
          }
        
        return (
             <Space direction="vertical" size={12}>
                <DatePicker
                  showTime
                  format="YYYY/MM/DD HH:mm"
                  minuteStep={15}
                  disabledDate={disabledDate}
                  disabledMinutes={disabledTimes}
                  onSelect={changeSelection}
                />
            </Space>
        );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM