将时区添加到此 js 计划?

Add timezone to this js schedule?

我有这个 javascript 代码来安排某些 div 的显示时间,但我遇到的问题是它没有使用设备时间或我们的时区。我真的需要它被分配到中央时区。

function displayMsg() {
    var currentTime = new Date();

    function toUTC(date) {
        return Date.UTC(
            date.getFullYear(),
            date.getMonth(),
            date.getDate(),
            date.getHours(),
            date.getMinutes(),
            date.getSeconds(),
            date.getMilliseconds()
        );
    }
    toUTC(currentTime);

    var startMsg1Time = new Date("2021-10-03T11:15:00Z");
    var endMsg1Time = new Date("2021-10-08T14:33:00Z");
    var startMsg2Time = new Date("2021-11-15T23:00:01Z");
    var endMsg2Time = new Date("2021-11-16T22:59:59Z");

    if (currentTime.getTime() > startMsg1Time.getTime() && currentTime.getTime() <= endMsg1Time.getTime()) {
        $('.Msg1').show();
    } else if (currentTime.getTime() > endMsg1Time.getTime) {
        $('.Msg1').hide();
    }

    if (currentTime.getTime() > startMsg2Time.getTime() && currentTime.getTime() <= endMsg2Time.getTime()) {
        $('.Msg2').show();
    } else if (currentTime.getTime() > endMsg2Time.getTime) {
        $('.Msg2').hide();
    }

}
displayMsg();

附带说明一下,这并没有完全达到我的需要。我正在尝试在每周日 8:30am-11:15am 和周五 7:00pm-8:15pm 显示消息。我打算使用这种方法,每次只创建一个时间表,但如果有人能推荐更好的方法,我很高兴听到。

您可以像下面的代码片段那样做一些事情,即只给出分钟和小时,然后检查是否 day = 1 (Monday)。我已经设置了闹钟时间11:25 PM11:35 PM(Monday)(你可以任意设置)

Use update of alarm according to need , here I have set 1sec using setInterval

Below snippet is for demo only , you can have any number of messages and alarm and specify day of alarm to come up or month (and can be year to which alarm ring)

setInterval(function() {
  var d = new Date();

  var Msg1Day = d.getDay();
  var Msg1TimeStart = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 25, 0, 0)
  var Msg1TimeEnd = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 35, 0, 0)

  if (Msg1Day === 1) {
    if (d >= Msg1TimeStart && d <= Msg1TimeEnd) {
      document.querySelector("#demo").innerHTML = "Alarm is ON"
      document.querySelector(".Msg1").innerHTML = "You already enjoyed Sunday, It's Monday Time and soon will Be Tuesday(Alarm is from 11:25 PM - 11:35 PM)"
    } else {
      document.querySelector("#demo").innerHTML = "Alarm is OFF"
      document.querySelector(".Msg1").innerHTML = ""
    }
  } else {
    document.querySelector("#demo").innerHTML = "Today is not monday"
  }
}, 1000);
<div class="Msg1"></div>
<div id="demo">Alaram status will be in 1sec and will be updated every second</div>