我有一个计时器。我必须设定一个要数到的日期。从当前时间到该日期进行计数,并在到达该日期时停止。我该如何使用JavaScript动态生成一个日期:Apr 4, 2020 18:20:25
。首先,我必须获取当前日期。我得到new Date().getTime()
的信息,然后说我希望计时器在60分钟后结束,因此通过添加new Date().getTime()
和60来设置结束日期。但是我不知道该怎么做?有人可以帮我弄这个吗?谢谢:)
// Set the date we're counting down to
var countDownDate = new Date("Apr 4, 2020 20:20:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's 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 minutes and seconds
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="timer"
document.getElementById("timer").innerHTML = minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<h1 id="timer"></h1>
无需使用getTime()
// Set the date we're counting down to
var countDownDate = new Date("Apr 4, 2020 20:20:25");
// Update the count down every 1 second
var countdownInterval = setInterval(function() {
// Get today's date and time
var now = new Date();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for minutes and seconds
var minutes = Math.floor(distance / 60000);
var seconds = Math.floor((distance - (minutes * 60000)) / 1000);
// Display the result in the element with id="timer"
document.getElementById("timer").innerHTML = minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(countdownInterval);
document.getElementById("timer").innerHTML = "EXPIRED";
}
}, 1000);
<h1 id="timer"></h1>