倒计时在凌晨3点,上午9点,下午3点和晚上9点重新开始

Countdown to restart at 3 AM, 9 AM, 3 PM and 9 PM

本文关键字:3点 9点 重新开始 下午 上午 倒计时 在凌晨      更新时间:2023-09-26

我正在寻找一个倒计时脚本,可以说"重新启动:x小时,x分钟和x秒。"在我的网站上我的服务器的概述。(用于每6小时重启一次的游戏服务器)

我找到了一个倒计时脚本,这样做,但我不知道如何运行它,这是脚本和我如何试图把它放在网站上。

var serverRestartHours = [3,9,15,21]; // in UTC
var startTime = new Date(); 
var hoursOffset = startTime.getTimezoneOffset()/60;
var currentHourUTC = startTime.getHours()+hoursOffset;
var nextRestartHour = 0;
for (i = 0; i < serverRestartHours.length; i++) {
if(serverRestartHours[i] > currentHourUTC){
    nextRestartHour = serverRestartHours[i];
    break;
}
}
if(currentHourUTC >= serverRestartHours[serverRestartHours.length-1])
nextRestartHour = serverRestartHours[0];
var endTime = new Date();
endTime.setMinutes(0);
endTime.setSeconds(0);
endTime.setHours(nextRestartHour-(endTime.getTimezoneOffset()/60));
console.log(endTime);
function update(){
var currentTime = new Date();
var remainingTime = new Date();
remainingTime.setTime(endTime.getTime()-currentTime.getTime());
if(remainingTime<0)
    return;
if(remainingTime.getHours()<=1)
    $("#note").text(remainingTime.getMinutes()+" minutes and "+remainingTime.getSeconds() + " seconds");
else
    $("#note").text(remainingTime.getHours()-1+" hours, "+remainingTime.getMinutes()+" minutes and "+remainingTime.getSeconds() + " seconds");
}
update();
setInterval(update,1000);

我试着在我的网站上包括这个(运行SMF与SimplePortal,试图在HTML块中实现这一点)

<div style="margin:12px;">Restart in: <span id="note"></span>
<script type="text/javascript" src="countdown.js"></script>
</div>

我这样做得到的是正常的字体说"重启在:"而不是"重启在:x小时,x分钟和x秒"

帮助任何人吗?

注意,setInterval在大约请求的时间间隔处运行,稍后它将逐渐漂移。如果你想让某些东西在合理的时间内更新,最好使用setTimeout并估计它需要等待多长时间。

同样,代码看起来比它需要的更冗长。如果从0300开始每隔6小时更新一次,您可以执行:

<script>
// Countdown in hh:mm:ss to next 0300, 0900, 1500 or 2100
// Uses local time
function timeToUpdate() {
  // Add leading zero to numbers less than 10
  function z(n) {return (n < 10? '0' : '') + n;}
  var now = new Date();
  // Calculate seconds to go, convert 60 to 00
  var secsToGo = (60 - now.getSeconds()) % 60;
  // Calculate minutes to go. If secs at 0, add 1
  var minsToGo = (59 - now.getMinutes() + !secsToGo) % 60;
  // Calculate hours to go. If secs and mins at 0, add 1
  var hoursToGo = 5 - ((now.getHours() + 3) % 6) + !(minsToGo + secsToGo); 
  // Return formatted string
  return z(hoursToGo) + ':' + z(minsToGo) + ':' + z(secsToGo);
}
function updateClock() {
  // Update counter
  document.getElementById('timeToGo').innerHTML = timeToUpdate();
  // Run just after next full second
  var lag = 1020 - (new Date()).getMilliseconds();
  setTimeout(updateClock, lag);
}
</script>
<button onclick="updateClock()">Start countdown</button>
<div>Restart in: <span id="timeToGo"></span></div>

以上使用本地时间,要使用UTC,请更改为UTC方法(例如now.getUTCHours())。