首页 > 解决方案 > 我如何能够将天转换为小时?

问题描述

现在,我可以毫无问题地显示天时分秒。但是这次我想要做的是花费几天,将它们转换为小时并显示它。

例如,如果我将计时器设置为从现在起三天后,我希望它显示72 hours 20 minutes 30 seconds. 请注意图片中没有日期,我不想显示3 days

我怎么能做到这一点?

var countDownDate  = new Date("6 June 2019 15:00:00");


        var options = {
            hour: 'numeric',
            minute: 'numeric',
            hour12: true
        };

        var countDate = countDownDate.toLocaleString('en-US', options);
        console.log(countDate);

        var now            = new Date().getTime();
        var timeDifference = countDownDate - now;
        var oneDay         = 1000 * 60 * 60 * 24;

        var days           = Math.floor(timeDifference / (oneDay));
        var hours          = Math.floor((timeDifference % (oneDay)) / (1000 * 60 * 60));
        var minutes        = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
        var seconds        = Math.floor((timeDifference % (1000 * 60)) / 1000);

        // Displays the clock counting down
        document.querySelector("#timer").innerHTML = `
        <span>${hours}   </br> hours</span>
        <span>${minutes} </br> minutes</span>
        <span>${seconds} </br> seconds!</span>`;

        if(timeDifference < 0) { 
            clearInterval(timer); 
            document.getElementById("timer").innerHTML = "Expired"; 
        }

标签: javascriptalgorithmdebugging

解决方案


每天等于 24 小时,所以只需将 24*days 添加到小时:)

更好的解决方案是这样计算小时数:

hours = Math.floor(timeDifference / (1000 * 60 * 60));

推荐阅读