我正在尝试将下面的倒计时时钟调整为大约几秒,以消除毫秒。
有什么建议吗?
<script type="text/javascript">
// Set the date we're counting down to
var countDownDate = new Date("Jan 1, 2018 00:00:01").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 an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (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 ="timmer"
document.getElementById("timmer").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}, 1000);
</script>
最佳答案
问题在这里:
var seconds = Math.floor(distance % (1000 * 60)) / (1000);
正确方法:
var seconds = Math.floor(distance % (1000 * 60) / (1000));
为什么?
因为您太早包装
Math.floor
。var countDownDate = new Date("Jan 1, 2018 00:00:01").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 an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor ((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor(distance % (1000 * 60) / (1000));
// CHANGES HERE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Display the result in the element with id ="timmer"
document.getElementById("timmer").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}, 1000);
<div id="timmer"></div>
关于javascript - 如何四舍五入到仅几秒(删除毫秒),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47570410/