I'm trying to make a function that gets current time and based on an array with open hours, shows if the shop is open or closed, and when it closes and opens.
This is my array with hours and it can't change, I mean, the hours can change, but overall how it works not.
{
"openHours": [
{ days: [1, 2, 3, 4, 5], from: '11:00', to: '22:00' },
{ days: [6], from: '12:00', to: '23:00' },
]
}
And as you can see, there is no day 0, which is Sunday, because the shop is closed then.
I have this for now
const [isOpen, setIsOpen] = useState(false);
const [opensAt, setOpensAt] = useState(false);
const [closesAt, setClosesAt] = useState(false);
const checkIfOpen = () => {
const now = new Date();
const openedHours = card.openHours.find(i => i.days.includes(now.getDay()));
const nextDay = new Date(Date.now() + 3600 * 1000 * 24);
const openedHoursNextDay = card.openHours.find(i => i.days.includes(nextDay.getDay()));
if (openedHours) {
const fromHours = new Date().setHours(...openedHours.from.split(':'));
const toHours = new Date().setHours(...openedHours.to.split(':'));
if (fromHours <= now.getTime() && now.getTime() <= toHours) {
setIsOpen(true);
setClosesAt(openedHours.to);
} else if (now.getTime() > toHours) {
setIsOpen(false);
setOpensAt(openedHoursNextDay.from);
} else {
setIsOpen(false);
setOpensAt(openedHours.from);
}
}
};
return (
<div className="info-text text-nowrap">
{isOpen ? `Closed at ${closesAt}` : `Opens at ${opensAt}`}
</div>
<div className="info-text">{isOpen ? "Now open" : "Now closed"}</div>
);
So I have a problem. If the next day is Sunday, openedHoursNextDay returns undefined, how can I get the next day that has open hours?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…