skip to Main Content

I have 2 DateTimePicker objects on my form, one for start time and one for end time … At the moment they work perfect, but i am able to choose an end time that is behind the start time … When i do this my calculations error. Is there any way to change the end_time picker to match the start_time picker after its been selected, and not allow it to choose date time before the start_time?

<Controller
    control={control}
    name='start_time'
    defaultValue={new Date(now.toLocaleString('en-US', { timeZone: timezone }))}
    render={({ field: { onChange, value } }) => (
        <DateTimePicker
            onChange={onChange}
            value={value ? new Date(value) : null}
            format="dd-MM-y h:mm a"
        />
    )}
/>




<Controller
    control={control}
    name='end_time'
    defaultValue={new Date(now.toLocaleString('en-US', { timeZone: timezone }))}
    render={({ field: { onChange, value } }) => (
        <DateTimePicker
            onChange={onChange}
            value={value ? new Date(value) : null}
            format="dd-MM-y h:mm a"
        />
    )}
/>

2

Answers


  1. Use the minimumDate

    <DateTimePicker
       onChange={onChange}
       value={value ? new Date(value) : null}
       format="dd-MM-y h:mm a"
       minimumDate=/* your start date */
    />
    

    UPD:
    Replying to your first comment:

    To change the minimumDate after changing the start date, you can do the following:

    const [startTime, setStartTime] = useState(new Date());
    const [endTime, setEndTime] = useState(new Date());
    
    const minEndTime = startTime;
    
    <DateTimePicker
         value={startTime}
         onChange={(_, newStartTime) => {
           setStartTime(newStartTime);
    
           // Update the minimum date for the end time picker
           setEndTime((prevEndTime) => {
             if (prevEndTime < newStartTime) {
               return newStartTime;
             }
             return prevEndTime;
           });
         }}
         format="dd-MM-y h:mm a"
    />
    ...
    <DateTimePicker
         value={endTime}
         onChange={(_, newEndTime) => {
            if (newEndTime >= startTime) {
              setEndTime(newEndTime);
            }
         }}
         minimumDate={minEndTime}
         format="dd-MM-y h:mm a"
    />
    

    https://wix.github.io/react-native-ui-lib/docs/components/form/DateTimePicker#minimumdate

    Login or Signup to reply.
  2. You can disable the end date, then enable it after selecting a start date

    You can follow this example

    enter image description here

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search