A while back I was tasked with a slightly unusual request. A client had 2 branches of the same business in different time zones. This caused a lot of confusion for their customers who would call a branch without realizing that branch has already closed.
The solution was to add a little ‘open or closed’ message next to the contact details for each branch.
In this article, I’m going to share a slimmed down version of a how to create an open / closed message using jQuery.
Getting the Time Right Now
Another very important note is getUTCHours uses UTC time which is the same as GMT. I added +2 because South Africa, where I live, is within the 2+ GMT time zone.
Setting the Time
Next, I concatenate the minutes to the hours. The reason for this is because the hours return a 0 – 23 value while the minutes return a 0 – 59 value. This gives us 1630 if it were half past six, for example.
Let’s assume you’ll be open between Monday to Friday from 9-5. Monday being day 1 and Friday being day 5. We can also then say the time for 9 o’clock would be 900 and 5o’clock is 1700.
Now we can check if the current day is between 1-5 and the time is between 900 and 1700.
Updating Your Open Status
For this example, I’m just going to update an empty div with the current open or closed status.
The very last step is the wrap the whole thing is a setInternal function to ensure this function runs every second or if you prefer every minute.
Here is the whole snippet. You can also see it working on jsfiddle.