Skip to content

Instantly share code, notes, and snippets.

@kidGodzilla
Last active July 31, 2023 04:22
Show Gist options
  • Save kidGodzilla/ac50551bd56c1bd2ce2232538b6458c5 to your computer and use it in GitHub Desktop.
Save kidGodzilla/ac50551bd56c1bd2ce2232538b6458c5 to your computer and use it in GitHub Desktop.
Is currently during working hours (Javascript)
// Example config for 9-5, M-F, PST (US)
var config = {
0: {
open: 1,
close: 0
},
1: {
open: 9,
close: 17
},
2: {
open: 9,
close: 17
},
3: {
open: 9,
close: 17
},
4: {
open: 9,
close: 17
},
5: {
open: 9,
close: 17
},
6: {
open: 1,
close: 0
},
offset: -7
};
Date.prototype.subHours = function (h) {
this.setTime(this.getTime() - (h * 60 * 60 * 1000));
return this;
}
function isWorkingHour (now) {
// Adjust remote user's time to match business time
now = now.subHours(config.offset + (now.getTimezoneOffset() / 60));
var day = now.getDay();
var hours = now.getHours();
// console.log(day, hours, config[day].open, config[day].close, config.offset);
return hours >= config[day].open && hours < config[day].close;
}
console.log(isWorkingHour(new Date()));
@hithismani
Copy link

Here's an adaptation, that adds support for 'exception' days that may have different working hours, with also support for MINUTES in working hour durations (so you can say the business is open from 9:30am instead of 9am):

  var config = {
    0: { open: 0, close: 0 }, // SUNDAY
    1: { open: 9, close: 17.5 },
    2: { open: 9, close: 17.5 },
    3: { open: 9, close: 17.5 },
    4: { open: 9, close: 17.5 },
    5: { open: 9, close: 17.5 },
    6: { open: 0, close: 0 }, // SATURDAY
    offset: 5.5, // TIMEZONE OFFSET. 5.5 is India/IST
    exceptions: {
      "2023-07-31": { open: 0, close: 0 }, // Christmas Day
      "2023-07-04": { open: 9, close: 13 }, // Independence Day
    },
  };
  
  function isWorkingHour(now) {
    now = now.subHours(config.offset + now.getTimezoneOffset() / 60);
  
    var day = now.getDay();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var currentTime = hours + minutes / 60;
  
    // Format the date as YYYY-MM-DD
    var dateString =
      now.getFullYear() +
      "-" +
      String(now.getMonth() + 1).padStart(2, "0") +
      "-" +
      String(now.getDate()).padStart(2, "0");
  
    // Check if the date is an exception
    if (config.exceptions.hasOwnProperty(dateString)) {
      return (
        currentTime >= config.exceptions[dateString].open &&
        currentTime < config.exceptions[dateString].close
      );
    } else {
      return currentTime >= config[day].open && currentTime < config[day].close;
    }
  }
  
  console.log(isWorkingHour(new Date()));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment