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

As you can imagine the first step is to get the current time in javascript. Keep in mind, when using getUTCDay, the week starts on a Sunday. Sunday is 0, Monday is 1 etc .

var day = new Date().getUTCDay();
var hours = new Date().getUTCHours() + 2;
var mins = new Date().getUTCMinutes();

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.

var time = parseInt(hours + '' + ("0" + mins).slice(-2));

Conditional Logic

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.

  if(day >= 1 && day <= 5) {
  	if(time >= 900 && time <= 1700) {
  		var status = 'open';
    }	else {
    	var status = 'closed';
    }
  } else {
  	var status = 'closed';
  }

Updating Your Open Status

For this example, I’m just going to update an empty div with the current open or closed status.

jQuery('.time').html(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.

setInterval( function() {

  var day = new Date().getUTCDay();
  var hours = new Date().getUTCHours() + 2;
  var mins = new Date().getUTCMinutes();

  var time = parseInt(hours + '' + ("0" + mins).slice(-2));

  if(day >= 1 && day <= 5) {
  	if(time >= 900 && time <= 1700) {
  		var status = 'open';
    }	else {
    	var status = 'closed';
    }
  } else {
  	var status = 'closed';
  }
  
  jQuery('.time').html(status);

}, 1000 );