open

Using Moment.js to show open/closed for business

Posted on Posted in Tips

This will need to be adjusted for timezone. Moment uses the end user’s time zone (browser based or client-side), not your website’s time zone (server-side) so this needs to be adjusted using moment tz (timezone) script. Fortunately for us, all of our foot traffic is based in the PST zone. The day of the week is set to numeric 1-7 values. We have different hours Saturday so there is an extra if/then for Saturdays. We are closed Sunday.

Using this is pretty simple. Go to https://momentjs.com/ to download moment.js or moment.min.js. These are the same file. If you are not planning to edit this file, use moment.min.js as it is minified (all the white space in eliminated to make a smaller file). Reference the file in your head section in script tags with something like:

src="/myjsfiles/moment.js"

Then add this in between script tags wherever you want it on your page and enjoy.

var currentDOW = moment().isoWeekday();
var currentTime= moment();
if (currentDOW <=5){
var startTime = moment('08:00 am', "HH:mm a");
var endTime = moment('06:00 pm', "HH:mm a");
amIBetween = currentTime.isBetween(startTime , endTime);
if (amIBetween == true){
	document.write('We are currently open. We close today at 6:00PM.');
}
else{
	document.write('We are currently closed.');
}

}

if (currentDOW ==6){
var startTime = moment('09:00 am', "HH:mm a");
var endTime = moment('06:00 pm', "HH:mm a");
amIBetween = currentTime.isBetween(startTime , endTime);
if (amIBetween == true){
	document.write('We are currently open. We close today at 6:00PM');
}
else{
	document.write('We are currently closed. We will be open again Monday at 8:00AM');
}
}
if (currentDOW ==7){
	document.write('We are currently closed. We will be open again on Monday at 8:00AM');
}

So when I place the script between two h1 tags I get: