首页 > 解决方案 > 每天每 12 小时显示剩余小时数

问题描述

我有这个 javascript 显示每 24 小时的剩余时间,它运行良好,但我想添加第二个函数来显示当天剩余的 12 小时。我如何在我当前的脚本中添加它

(function() {
  var start = new Date;
  start.setHours(5, 0, 0); // military time, remaining time until 5 


  function pad(num) {
    return ("0" + parseInt(num)).substr(-2);
  }

  function tick() {
    var now = new Date;
    if (now > start) { 
      start.setDate(start.getDate() + 1);
    }
    var remain = ((start - now) / 1000);
    var hh = pad((remain / 60 / 60) % 60);
    var mm = pad((remain / 60) % 60);
    var ss = pad(remain % 60);
    document.getElementById('time24').innerHTML =
      hh + ":" + mm + ":" + ss;
    setTimeout(tick, 1000);
  }
 document.addEventListener('click', tick);
})();
<h2>Starts at 5am</h2>
<h4>Respawn Time every 24 hours</h4><br>
<b id="time24"></b> Until respawn<br>

<h4>Respawn Time every 12 hours</h4><br>
<b>??:??:??</b> Until respawn

编辑:

例如,此脚本显示凌晨 5 点之前的剩余小时数并重置(因此它会在凌晨 5 点重置)。

我需要的第二个功能是显示一天中前 12 小时的剩余时间,然后重置。

因此,如果第一个函数的剩余时间为 24:00,则第二个函数应显示 12:00

标签: javascript

解决方案


您可以使用

var hh = pad((remain / 60 / 60) % 60 % 12);

得到小时模数 12。

(function() {
  const start = new Date;
  start.setHours(5, 0, 0); // military time, remaining time until 5 


  function pad(num) {
    return ("0" + parseInt(num)).substr(-2);
  }

  function tick() {
    const now = new Date;
    if (now > start) { 
      start.setDate(start.getDate() + 1);
    }
    const remain = ((start - now) / 1000);
    const hh = pad((remain / 60 / 60) % 60);
    const hh12 = pad((remain / 60 / 60) % 60 % 12);
    const mm = pad((remain / 60) % 60);
    const ss = pad(remain % 60);
    document.getElementById('time24').innerHTML =
      hh + ":" + mm + ":" + ss;
    document.getElementById('time12').innerHTML =
      hh12 + ":" + mm + ":" + ss;
    setTimeout(tick, 1000);
  }
 document.addEventListener('click', tick);
})();
<h2>Starts at 5am</h2>
<h4>Respawn Time every 24 hours</h4><br>
<b id="time24"></b> Until respawn<br>

<h4>Respawn Time every 12 hours</h4><br>
<b id="time12"></b> Until respawn


推荐阅读