javascript - 如何四舍五入到只有秒(删除毫秒)

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

最佳答案

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

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

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

var seconds = time - minutes * 60;

现在,如果您也想获得完整的小时数,请先将总秒数除以 3600 (60 分钟/小时 * 60 秒/分钟),然后计算剩余秒数:

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

关于javascript - 如何四舍五入到只有秒(删除毫秒),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47570410/

相关文章:

html - 我的链接不再可点击,因为它位于其他元素后面

html - 如果HTTP是超文本传输​​协议(protocol),我们如何上传文件和图片呢?

javascript - Axios 不在请求中传递 header

javascript - 如果 (!document.images)

javascript - 如何为覆盖全屏宽度且不溢出的元素设置动画

javascript - 为什么我不能从图像 map 制作 SVG?

Javascript 减少功能后不起作用?

html - 隐藏 css <span> @min-width : 480px

javascript - getElementsByTagName() 方法没有按预期工作

iphone - 为什么 Brightcove 播放器未在 UIWebview 中加载?