【发布时间】:2019-02-06 15:44:15
【问题描述】:
我设法以 H:M:S 格式显示倒数计时器。
我可以知道如何将其显示为 HH:MM:SS 格式吗?例如,假设 300 小时 1 分 1 秒,它将显示为 300:01:01 而不是 300:1:1。
这是我目前得到的。
// Set the date we're counting down to
var countDownDate = new Date("Aug 31, 2019 22:55:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = hours + " : "
+ minutes + " : " + seconds + "";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
【问题讨论】:
-
看看moment.js
-
@itdoesntwork 这个问题当然不需要 moment.js.. 我感觉 moment.js 正在成为新的 jQuery...
-
@FabioManzano 它似乎不是那个的副本。
-
添加一个 '0',读取最后 2 个字符:
('0' + minutes).slice(-2)
标签: javascript jquery html