Ad

Does Check Day And Hour Need To Check Timezone?

My code to check day and hour like this :

function checkDay() {
  var day = new Date();
  if (day.getDay() >= 1 && day.getDay() <= 5 && day.getHours() >= 9 && day.getHours() < 17) {
    return true;
  } else {
    return false;
  }
}

I want every Monday to Friday 9 to 17, it's true. Apart from that, it is false

I had test it and it works. Is it necessary to check Timezone?

My position at Indonesia (GMT + 7)

If I implement timezone, it like this :

function checkDay() {
  const offsetHours = new Date().getTimezoneOffset() / 60;
  const day = new Date();

  day.setHours(day.getHours() + offsetHours);

  return day.getDay() >= 1 && day.getDay() <= 5 && day.getHours() >= 2 && day.getHours() < 10;
}

Is it necessary to check Timezone like that?

Ad

Answer

Your first piece of code is already correct because getHours and getDay already operate in the local time zone. As per the MDN Date documentation:

Note: It's important to keep in mind that while the time value at the heart of a Date object is UTC, the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.

Likewise the ECMAScript specifications (e.g. ECMA 262, 2015 edition) describe the behaviour as going via the LocalTime abstract operation:

The abstract operation LocalTime with argument t converts t from UTC to local time

Ad
source: stackoverflow.com
Ad