每小时倒计时一次,但以30分钟为单位



我需要一个简单的倒计时计时器,但由于某种原因,我似乎无法获得它,这真的很困扰我,我认为这是因为我需要它的特殊方式,它必须遵守以下规则:

  • 必须每小时一次
  • 必须在30分钟内
  • 必须使用UTC时间

例如,现在是世界协调时07:22,距离下一次还有8分钟
如果是07:30,它会说离下一个小时还有一个小时
最后但同样重要的是,如果是07:31,那么距离下一场比赛还有59分钟。

对于我做的其他倒计时,我可以很容易地做到这一点,但这些都是针对小时型的事情,并没有那么复杂。。。我只是被难住了,请帮帮我。

编辑增加了样本代码

        var d = new Date();
        var hoursUntil = 2 - d.getUTCHours() % 3;
        var minutesUntil = 60 - d.getUTCMinutes();
        var timestr = "";
        if (minutesUntil === 60) {
            hoursUntil++;
            minutesUntil = 0;
        }
        if (hoursUntil > 0) {
            timestr += hoursUntil + " hour" + (hoursUntil > 1 ? "s" : "");
        }
        if (hoursUntil >= 1 && minutesUntil > 1) {
            timestr += " and " + minutesUntil + " minute" + (minutesUntil > 1 ? "s" : "");
        }
        if (minutesUntil > 1 && hoursUntil < 1) {
            timestr += minutesUntil + " minute" + (minutesUntil > 0 && minutesUntil < 2 ? "" : "s");
        }
        bot.sendMessage(msg, "Next event will be in " + timestr + ".");

让我们思考一下。我们想知道的是,下一次分针什么时候显示30。如果我们只想每半小时知道一次,我们可以像你对d.getUTCHours() % 3所做的那样,在30之前完成剩下的除法。

然而,我们希望每60分钟一次,所以我们必须做somethingInMinutes % 60。标记必须从60变为0,所以只需增加30分钟。

要获得秒精度,请将其计算为秒,将当前秒相加,然后从60分钟(3600秒)中减去。

我们想要一个每一秒都能触发的计时器。计算1000和毫秒的差值。

<div>Seconds remaining until next 30 minutes mark: <span id="min-total"></span></div>
<div>minutes:seconds remaining: <span id="min-part"></span>:<span id="sec-part"></span></div>
<script>
  var byId = document.getElementById.bind(document);
  function updateTime()
  {
    var
      time = new Date(),
      // take 1800 seconds (30 minutes) and substract the remaining minutes and seconds
      // 30 minutes mark is rest of (+30 divided by 60); *60 in seconds; substract both, mins & secs
      secsRemaining = 3600 - (time.getUTCMinutes()+30)%60 * 60 - time.getUTCSeconds(),
      // integer division
      mins = Math.floor(secsRemaining / 60),
      secs = secsRemaining % 60
    ;
    byId('min-total').textContent = secsRemaining;
    byId('min-part').textContent  = mins;
    byId('sec-part').textContent  = secs;
    // let's be sophisticated and get a fresh time object
    // to calculate the next seconds shift of the clock
    setTimeout( updateTime, 1000 - (new Date()).getUTCMilliseconds() );
  }
  updateTime();
</script>

也许我错过了什么,但据我所见,UTC和实际上的小时数与此无关。它应该像计算当前分钟在哪里一样简单

也许像

now = new Date();
minutes = now.getMinutes();
if(minutes > 30) {
    minutes_until = (60 - minutes) + 30;
    }
else {
    minutes_until = 30 - minutes;
    }

最新更新