Iggy's Pop
Iggy's Pop

Reputation: 599

Show different times based on day

I am trying to exclude different times based on dates but the times are disabled no matter what dates I pick. For example if I select the 28th Of September then 12 o'clock should be disabled. If I choose the 3rd of October then 1pm should disabled, however 12 and 1 are disabled right from the start and stay that way no matter what date I pick.

https://hacker0x01.github.io/react-datepicker

  const isSunday = (date) => {
    const day = getDay(date);
    return day !== 0;
  };

  let excluded = [
    {
      time: "12",
      date: "28/09/2020",
    },
    {
      time: "13",
      date: "03/10/2020",
    },
  ];


    <DatePickerField
      filterDate={isSunday}
      minTime={new Date(new Date().setHours(8, 0, 0))}
      maxTime={new Date(new Date().setHours(17, 0, 0))}
      excludeTimes={excluded.map((exclude, index) => {
        return setHours(
          setMinutes(new Date(), 0),
          parseInt(exclude.time)
        );
      })}
      timeIntervals={60}
      maxDate={addDays(new Date(), 3)}
      dateFormat="d/M/Y HH:mm"
      timeFormat="HH:mm"
      name="time-to-contact"
      label="Required Date *"
    />

Upvotes: 0

Views: 67

Answers (1)

someRandomDev
someRandomDev

Reputation: 1246

The problem is you are always returning excluded in excludeTimes props. You need to return the time only if the selected date is the date. Something like that should work. (By adding const [value, setValue] = useState(); too).

<DatePickerField
  filterDate={isSunday}
  minTime={new Date(new Date().setHours(8, 0, 0))}
  maxTime={new Date(new Date().setHours(17, 0, 0))}
  excludeTimes={excluded.map((exclude) => {
    const excDate = new Date(exclude.date);
    if (
      value &&
      excDate.getDate() === value.getDate() &&
      excDate.getFullYear() === value.getFullYear() &&
      excDate.getMonth() === value.getMonth()
    ) {
      return new Date(new Date().setHours(exclude.time, 0, 0));
    }
    return null;
  })}
  timeIntervals={60}
  maxDate={addDays(new Date(), 3)}
  dateFormat="d/M/Y HH:mm"
  timeFormat="HH:mm"
  name="time-to-contact"
  label="Required Date *"
  onChange={(e) => {
    setValue(new Date(e));
  }}
  selected={value}
    />

Also your dates are not in the good format for JS, it should be:

  const excluded = [
    {
      time: "12",
      date: "09/28/2020"
    },
    {
      time: "13",
      date: "10/03/2020"
    }
  ];

Here's a link to a working example: https://codesandbox.io/s/competent-smoke-4nv1e?file=/src/App.js

To add exclude time for a specific day (let's say monday) you could use this:

const excluded = [
  {
    time: "12",
    day: 1
  }, 
]

And set the prop to this:

excludeTimes={excluded.map((exclude) => {
  if (value && value.getDay() === exclude.day) {
    return new Date(new Date().setHours(exclude.time, 0, 0));
  }
  return null;
})}

Upvotes: 1

Related Questions