Hacker0x01 / react-datepicker

A simple and reusable datepicker component for React
https://reactdatepicker.com/
MIT License
8.06k stars 2.24k forks source link

Disable time selected #3727

Open Mzomuhle25 opened 2 years ago

Mzomuhle25 commented 2 years ago

Hi, I am using a datepicker for my booking system, I need a solution for disabling all the time slots selected so other users wouldn't book the exact time.

Thank you in advance.

Muhiq146 commented 2 years ago

Hi,

I got a solution which is working properly, sharing with you.



Firstly make an array of the slots which you want to be disabled like this



let slots = [
{ start: "08/09/2022 13:00", end: "08/09/2022 14:00" },
{ start: "08/09/2022 3:00", end: "08/09/2022 5:00" },
{ start: "18/08/2022 12:00", end: "18/08/2022 4:00" },
{ start: "01/09/2022 9:00", end: "02/09/2022 1:00" },
]

You can define a object in any proper format or using Date function like this


// { start: "08/09/2022 13:00", end: "08/09/2022 14:00" }
// OR
// { start: new Date(2022, 8, 8, 3), end: new Date(2022, 8, 8, 5) }

Now use filterTime prop of react-datepicker

filterTime={(time) => {
                  for (let i = 0; i < slots.length; i++) {
                    const e = slots[i];

                    var x = moment(time),
                      beforeTime = moment(e.start, "DD/MM/YYYY hh:mm"),
                      // Note 
                      Please check that the format which you define here 
                      should be same as you have given in the slots array.
                      //   //
                      afterTime = moment(e.end, "DD/MM/YYYY hh:mm");

                    if (
                      x.isBetween(beforeTime, afterTime) ||
                      x.isSame(moment(beforeTime)) ||
                      x.isSame(moment(afterTime))
                    ) {
                      return false;
                    }
                    if (i + 1 == slots.length) {
                      return true;
                    }
                  }
                }}
github-actions[bot] commented 3 months ago

This issue is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 10 days.