Opening hours component in React with time zones
The first "Open now" badge I shipped for a client lied. The salon was in Zurich, the site was deployed on servers in the US, and I was testing from my laptop at home. It showed "Open" at 11 pm because somewhere in the chain a date was created in the wrong time zone. That bug is the reason the Opening hours component and the Open now badge in Facade compute everything in the business's own IANA…
When a salon in Zurich displays an "Open now" badge, it shows "Open" at 11 pm, due to a time zone discrepancy. This issue led to the creation of the Opening hours component and the Open now badge in React, which compute everything in the business's own IANA time zone. The source code for this component is provided below.
The function `getZonedNow` takes a `Date` object and a `timeZone` string as parameters. It uses the `Intl.DateTimeFormat` API to format the date in the specified time zone and extract the day and minutes since midnight. The resulting object includes a `day` property (representing the day of the week as a numeric index) and a `minutes` property (representing the current time as minutes since midnight).
The component works with a weekly map, where each day contains an array of ranges. These ranges represent the salon or restaurant's opening hours throughout the week. If a day is closed, the array is null, empty, or missing. When there are multiple ranges, it indicates a split shift.
The component renders "Closed" for days with no data and joins the ranges of a split day using a comma. For ranges that close after midnight, such as a bar open until 02:00, the time is treated as belonging to the next day. To highlight the current day, the component uses the `getZonedNow` function to determine the current day based on the business's time zone, ensuring that the user sees the correct day regardless of their local time zone.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.