如何使用javascript计算小时,分钟,秒

时间:2016-08-20 09:02:21

标签: javascript

我已经创建了一个在线考试系统,我在在线考试系统中安装了一个倒数计时器。以下是我的javascript代码。 Plz检查

<h2><p style="float: right" id="countdown"></p></h2>

<script>
    $(document).ready(function () {
 $examination_test_id = $("#examination_test_id").val();
        $time_limit = $("#time_limit").val();
        var d = new Date($time_limit);  //14-August-2016 01:20:00
        var hours = d.getHours();       //01
        var minute = d.getMinutes();    //20
        var minutes = hours * 60 + minute;
        var seconds = 60 * minutes;     //00
        console.log(seconds);
        if (typeof (Storage) !== "undefined") {      //checks if localStorage is enabled
            if (sessionStorage.seconds) {                       //checks if seconds are saved to localstorage
                seconds = sessionStorage.seconds;

            }
        }
        function secondPassed() {
            var minutes = parseInt((seconds) / 60);
            var hours = parseInt(minutes / 60);
            var remainingSeconds = seconds % 60;
            if (remainingSeconds < 10) {
                remainingSeconds = "0" + remainingSeconds;
            }

            if (typeof (Storage) !== "undefined") {
                sessionStorage.setItem("seconds", seconds);
            }

            document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;

            if (seconds == 0) {
                clearInterval(myVar);
                document.getElementById('countdown').innerHTML = alert('Timeout');
                window.location.href = base_url + "student/Examinations/check_answer/" + $examination_test_id;

                if (typeof (Storage) !== "undefined") {
                    sessionStorage.removeItem("seconds");
                }
            } else {
                seconds--;
            }
        }
        var myVar = setInterval(secondPassed, 1000);

    });
});
</script>

我的问题:coundown计时器应该从01:20:00开始,但在我的情况下,倒数计时器从01:80:00开始,为什么?请检查我的javascript代码

3 个答案:

答案 0 :(得分:0)

var minutes = hours * 60 + minute;

一小时二十分钟总计80分钟。您应该将该行更改为var minutes = minute;

答案 1 :(得分:0)

几分钟后,你就拿走了总数,

var minutes = hours * 60 + minute;
     80= 1*60 + 20

答案 2 :(得分:0)

我在不到5秒的时间内找到答案:Javascript return number of days,hours,minutes,seconds between two dates

JavaScript seconds to time string with format hh:mm:ss

所以请在发布此类问题之前先搜索一下