JavaScript中的时间格式H:M:S

时间:2018-09-04 09:56:27

标签: javascript php jquery

使用以下代码,我以秒为单位获取结果,但是我想以H:m:s格式获取结果,例如,如果我以63秒获取结果,那么结果应显示为1:03,我该怎么做? >

<html>
<head>
    <title>Start and Stop a Timer using JavaScript by DevCurry.com</title>
    <script type="text/javascript">
        var check = null;

       window.onload = function(e) {
            if (check == null) {
                var cnt = 0;

                check = setInterval(function () {
                    cnt += 1;
                    document.getElementById("para").innerHTML = cnt;
                }, 1000);
            }
        };

        function stop() {
            clearInterval(check);
            check = null;
            document.getElementById("para").innerHTML = '0';
        }
    </script>
</head>
<body>
<div>
    <p id="para">0</p>
    <input id="btnStart" type="button" value="Start"
        onclick="printDuration();" />
    <input id="btnStop" type="button" value="Stop"
        onclick="stop();" />
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

尝试一下:

function secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
    var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
    var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
    return hDisplay + mDisplay + sDisplay; 
}

答案 1 :(得分:0)

您必须调用function并返回计算值,例如从秒到分钟和小时,如下所示:

 var check = null;

       window.onload = function(e) {
            if (check == null) {
                var cnt = 0;

                check = setInterval(function () {
                    cnt += 1;
                   var val = secondsToHms(cnt)
                    document.getElementById("para").innerHTML = val;
                }, 1000);
            }
        };

      function stop() {
          clearInterval(check);
          check = null;
          document.getElementById("para").innerHTML = '0';
      }
        
      function secondsToHms(sec) {
        sec = Number(sec);
        var h = Math.floor(sec / 3600);
        var m = Math.floor(sec % 3600 / 60);
        var s = Math.floor(sec % 3600 % 60);

        var hour = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
        var minute = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
        var second = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
        return hour + minute + second; 
    }
<html>
<head>
    <title>Start and Stop a Timer using JavaScript by DevCurry.com</title>
</head>
<body>
<div>
    <p id="para">0</p>
    <input id="btnStart" type="button" value="Start"
        onclick="printDuration();" />
    <input id="btnStop" type="button" value="Stop"
        onclick="stop();" />
</div>
</body>
</html>