Home > Software design >  Limit time range selection
Limit time range selection

Time:06-11

On my site, the user has the opportunity to select the date-time range. I implement this using the DatePicker from the react-datepicker library.

I set up the date range in such a way that the end date could not be less than the start date (which is quite logical). That is, for the end date, the user can select dates only after the start date (or itself). It works.

But I have problems to set up exactly the same functionality over time. This is complicated by the fact that I need to set the time range up to seconds.

So I will explain with an example what I need: If the user has selected a start date and time of 11/06/2022 12:20:20, then the time in the end date must start from 12:20:20.

To understand what I have at the moment, I will leave a gif

enter image description here

    () => {
  const [startDate, setStartDate] = useState(new Date());
  const [endDate, setEndDate] = useState(new Date());
  return (
  <>
    <DatePicker
      selected={startDate}
      onChange={(date) => setStartDate(date)}
      showTimeSelect
      timeFormat="HH:mm:ss"
      timeIntervals={1}
      isClearable
      timeCaption="Time"
      dateFormat="dd/MM/yyyy    HH:mm:ss"
      
      selectsStart
      startDate={startDate}
      endDate={endDate}
    />
    
    <DatePicker
      selected={endDate}
      onChange={(date) => setEndDate(date)}
      showTimeSelect
      isClearable
      timeFormat="HH:mm:ss"
      timeIntervals={1}
      timeCaption="time"
      dateFormat="dd/MM/yyyy    HH:mm:ss"
      
      selectsEnd
      startDate={startDate}
      endDate={endDate}
      minDate={startDate}
    />
    </>
  );
};

CodePudding user response:

Problem

The issue is minDate is only applicable for selecting the date

Solution

  1. Define a function to filter the time you want to allow like below. time input is what the user going to select.
const filterPassedTime = (time) => {
  const selectedDate = new Date(time);
  return selectedDate.getTime() > startDate.getTime();
};
  1. Set the above time filter function to the second input using filterTime prop like below.
<DatePicker
  ...
  ...
  filterTime={filterPassedTime}
/>

Working Example

Edit ecstatic-jang-hbymj0

  • Related