user3348410
user3348410

Reputation: 2833

React-datepicker minTime and maxTime not works

I have DatePicker on my form and;

i'm using this package: [https://reactdatepicker.com/#example-specific-time-range][1]

on the selection start date: I want to make disable all times before the current time. So if now 3 AM. before hours (2 AM, 1 AM, 12 AM) will be disabled.

Usually, it's making like that: But here they write static time, I want to add there current hour of the current time.

<DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      showTimeSelect
      minTime={setHours(setMinutes(new Date(), 0), 17)}
      maxTime={setHours(setMinutes(new Date(), 30), 20)}
      dateFormat="MMMM d, yyyy h:mm aa"
    />

So i saw some examples about that and trying this:

const now = moment().toDate();

<DatePicker
                    selected={this.state.startDate}
                    onChange={event => this.getStartDate(event)}
                    showTimeSelect
                    timeFormat="haa"
                    timeIntervals={60}
                    minDate={now}
                    minTime={now.hours(now.hour()).minutes(now.minutes())}
                    maxTime={now.hours(23).minutes(45)}
                    dateFormat="MM/d/yyyy hhaa"
                    timeCaption="Hour"
                  />

but nothing happened. Where I make a mistake?

Upvotes: 3

Views: 14208

Answers (2)

Samuel Jones
Samuel Jones

Reputation: 73

Filtering passed times works for me using the filterTime prop. Here's a link to the snippet from the docs:

https://reactdatepicker.com/#example-filter-times

Essentially, this is what you need to do:

() => {
  const [startDate, setStartDate] = useState(null);
  
  const filterPassedTime = (time) => {
    const currentDate = new Date();
    const selectedDate = new Date(time);

    return currentDate.getTime() < selectedDate.getTime();
  };

  return (
    <DatePicker
      selected={startDate}
      onChange={(date) => setStartDate(date)}
      showTimeSelect
      filterTime={filterPassedTime}
      dateFormat="MMMM d, yyyy h:mm aa"
    />
  );
};

You also won't need to use any external libraries e.g. date-fns

Upvotes: 7

Teddy Sterne
Teddy Sterne

Reputation: 14221

You can use the libraries built in time functions to set the time correctly. Since the min hours is the current hour that you want then you only need to use setMinutes to set the minutes back to 0. The resulting code should look something like this:

<DatePicker
  selected={now}
  onChange={event => this.getStartDate(event)}
  showTimeSelect
  timeFormat="haa"
  timeIntervals={60}
  minDate={now}
  minTime={setMinutes(now, 0)}
  maxTime={setHours(setMinutes(now, 45), 23)}
  maxDate={now}
  dateFormat="MM/d/yyyy hhaa"
  timeCaption="Hour"
/>

Checkout a demo here: https://stackblitz.com/edit/react-time-picker-demo

Upvotes: 1

Related Questions