javascript - 每天每 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
解决方案
您可以使用
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
推荐阅读
- java - 正则表达式获取最后一个值
- node.js - 将 promiseAll 转换为渐进式 promise 解决(例如每 3 个promises)不起作用
- java - 如何在 smooks 中设置语言环境
- ios - NavigationLink 似乎只占用很小的空间
- r - 如何转置特定列值的数据框?
- javascript - javascript AudioNodes不能改变采样率
- python - BeaitifulSoup 无法读取所有命名空间
- gstreamer - GStreamer 'rawvideoparse' 元素读取错误的字节数
- angular - 角度验证器和双向绑定问题
- python - 无法重塑不存在的张量