如何舍入到仅秒(删除毫秒)

时间:2017-11-30 09:51:29

标签: javascript html

我正在尝试将以下倒计时时钟转换为秒,以消除毫秒。

有什么建议吗?

<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>

3 个答案:

答案 0 :(得分:3)

要获得完整分钟数,您必须将总秒数除以60(60秒/分钟):

var minutes = Math.floor(time / 60);

要获得剩余的秒数,您必须将完整的分钟数乘以60并从总秒数中减去:

var seconds = time - minutes * 60;

现在,如果您还希望获得整个小时数,请先将总秒数除以3600 (60 minutes/hour * 60 seconds/minute),然后计算剩余秒数:

var hours = Math.floor(time / 3600);
time = time - hours * 3600;

答案 1 :(得分:1)

最简单的解决方案是使用parseInt(秒)

答案 2 :(得分:0)

问题在于:

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>