react-datepicker select time range for single day

10.1k views Asked by At

I am using react-datepicker to build a booking system component. Users can select a day and select a start time and end time (both start and end time can only be in the same day).

I would like to show only one datepicker and then two timepicker, but only manage to get two full components (date+time).

My code:

const StartTime () => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      showTimeSelect
      timeFormat="HH:mm"
      timeIntervals={15}
      timeCaption="time"
      dateFormat="MMMM d, yyyy h:mm aa"
    />
  );
};

const EndTime () => {
  const [endDate, setEndDate] = useState(new Date());
  return (
    <DatePicker
      selected={endDate}
      onChange={date => setEndDate(date)}
      showTimeSelect
      timeFormat="HH:mm"
      timeIntervals={15}
      timeCaption="time"
      dateFormat="MMMM d, yyyy h:mm aa"
    />
  );
};
1

There are 1 answers

2
Amr Hosni On

You can use 1 date only picker and two time only pickers. You will need to validate the start time to be before the end.

Date only picker

   const date () => {
      const [startDate, setStartDate] = useState(new Date());
      return (
        <DatePicker selected={startDate} onChange={date => setStartDate(date)} />
      );
    };

Time only Picker

const EndTime() => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      showTimeSelect
      showTimeSelectOnly
      timeIntervals={15}
      timeCaption="Time"
      dateFormat="h:mm aa"
    />
  );
};