检查日期和时间是否需要检查时区?

Does check day and hour need to check timezone?

我的代码是这样检查日期和时间的:

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

我想要每周一到周五的 9 点到 17 点,是的。除此之外就是false

我已经测试过它并且有效。是否需要检查时区?

我在印度尼西亚的位置 (GMT + 7)

如果我实现时区,它是这样的:

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;
}

有必要这样检查时区吗?

您的第一段代码已经正确,因为 getHoursgetDay 已经在本地时区运行。根据 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.

同样,ECMAScript 规范(例如 ECMA 262, 2015 edition)将行为描述为通过 LocalTime 抽象操作:

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