0

I am using React to create online food ordering and I need to disable the ordering when the restaurant is closed, until it opens again.

something like this:

  const time = new Date().toLocaleTimeString("rs-RS");
  const day = new Date().getDay();

  if (day <= 5 && time < "08:00:00" && time > "23:30:00") {
    console.log("closed");
  } else if (day === 6 && time < "09:00:00" && time > "23:30:00") {
    console.log("closed");
  } else if (day === 0 && time < "12:00:00" && time > "20:00:00") {
    console.log("closed");
  } else {
    console.log("open");
  }

Thanks.

Gilles Heinesch
  • 2,889
  • 1
  • 22
  • 43
Madizm
  • 381
  • 1
  • 3
  • 9

1 Answers1

0

You can't compare a Date with a String. I would use Date.setHours():

 const time = new Date();
  const day = new Date().getDay();

  if ((day <= 5) && (time < (new Date().setHours(8)) && (time > (new Date().setHours(23, 30))) {
    console.log("closed");
  } else if ((day === 6) && (time < (new Date().setHours(9)) && (time > (new Date().setHours(23, 30))) {
    console.log("closed");
  } else if ((day === 0) && (time < (new Date().setHours(12)) && (time > (new Date().setHours(20))) {
    console.log("closed");
  } else {
    console.log("open");
  }
Gilles Heinesch
  • 2,889
  • 1
  • 22
  • 43
  • Thanks for the reply, it looks like the time is not correct and the console is not gettting the print right. Must be something with time format. – Madizm Apr 06 '21 at 17:16
  • i've edited the code. Can you try it again please? @Madizm – Gilles Heinesch Apr 06 '21 at 18:19
  • still not working, the format of the hours is incorrect, new Date().setHours(12), when i console log it, it's showing random numbers. – Madizm Apr 07 '21 at 14:44
  • Does it work now? I've removed the timezone @Madizm You can set if afterwards: https://stackoverflow.com/questions/439630/create-a-date-with-a-set-timezone-without-using-a-string-representation – Gilles Heinesch Apr 07 '21 at 15:51