0

我正在尝试建立一个总是提前 6 天的小时/分钟/秒倒计时。

诀窍是,倒计时应该在每天 16:00 重置,而不是 24:00,并且应该以 24 小时格式显示日期。

日期应在时钟下方注明为“月(九月),日(13)”

这就是我想出的:

function ShowTimes() {
  var now = new Date();
  now.setDate(now.getDate() + 5)
  if (now.getHours() > 14) {
  var hrs = 39-now.getHours();
} else {
    var hrs = 16-now.getHours();
}
  var mins = 59-now.getMinutes();
  var secs = 59-now.getSeconds();
  var str = '';
      str = now.toString();
      str += '<br>'+hrs+' hours '+mins+' minutes '+secs+' seconds ';
  document.getElementById('countdownToFour').innerHTML = str;

  if (hrs < 0) {
    hrs = 23-now.getHours();
    now.setDate(now.getDate() + 6);
  }
}
var _cntDown;
function StopTimes() {
    clearInterval(_cntDown);
}

问题是我不知道如何将其设置为 24 小时制以及如何将其重置为 16.00 而不是 24.00。我似乎已经设法提前 6 天设置它,但我不太确定......

4

1 回答 1

0

因为很难理解你的代码,所以我创建了一个新的计数器:

<html>
 <head>
  <script type="text/javascript">
   var counterIntervalVar;
   var howManyDaysAhead = 0;
   var finishHours = 16;
   var finishMinutes = 0;
   var finishSeconds = 0;
   function ShowTimes()
   {
    var str = "";
    var now = new Date();//Use current time as start time

    //Creating the target time
    var dayIncreasion = 1000 * 3600 * 24 * howManyDaysAhead;
    var targetDateInMilliSeconds = now.getTime();
    var targetDate = new Date(targetDateInMilliSeconds + dayIncreasion); 
    targetDate.setHours(finishHours);
    targetDate.setMinutes(finishMinutes);
    targetDate.setSeconds(finishSeconds);
    targetDateInMilliSeconds = targetDate.getTime();

    //Calculate and show the difference between current time and target time
    var timeDifference = targetDateInMilliSeconds - now.getTime();
    if (timeDifference >= 0)
    {
     var hrs = Math.floor(timeDifference / 1000 / 3600);
     var mins = Math.floor(timeDifference / 1000 / 60) - (hrs * 60);
     sec = Math.floor(timeDifference / 1000) - (hrs * 3600) - (mins * 60);
     str += '<br>'+hrs+' hours '+mins+' minutes '+sec+' seconds ';
     document.getElementById('countdownToFour').innerHTML = str;
    } else {
     howManyDaysAhead++;
    }

    //Give the 'if' query a realistic condition
    if (str == 'x')
    {
     //Stop the loop
     window.clearInterval(counterIntervalVar);
    }
   }

   function initCountdown()
   {
    counterIntervalVar = window.setInterval("ShowTimes()",999);
   }
  </script>
 </head>
 <body onLoad="initCountdown()">
  <div id="countdownToFour"></div>
 </body>
</html>

希望这个例子对你有用,或者至少引导你走上正确的道路。

于 2013-09-10T13:36:20.213 回答