格式化Countup Timer Javascript

时间:2011-01-20 21:50:34

标签: javascript time

我使用以下代码显示计时时钟 分钟和秒格式正常,但小时显示为负数,例如“-238”

     <script language="javascript" type="text/javascript">
        var startTime = new Date(2011,01,21,08,55, 0)

        $(document).ready(function () {
            setTimeout(updateClock, 1000);
        });
        function updateClock() {
            var timeField = $(".timeSince");
            var currentTime = new Date();
            var difference =  currentTime - startTime;
            timeField.html(MillisecondsToDuration(difference));
            setTimeout(updateClock, 1000);
        }
        function MillisecondsToDuration(n) {                 
            var hms = "";                    

            var dtm = new Date();                 
            dtm.setTime(n);              
            var h = "000" + Math.floor(n / 3600000);              
            var m = "0" + dtm.getMinutes();         
            var s = "0" + dtm.getSeconds();        


            hms = h.substr(h.length-4) + " hours, " + m.substr(m.length-2) + " mins, ";                
            hms += s.substr(s.length-2) + " secs";
            return hms;              
        } 
       </script>

1 个答案:

答案 0 :(得分:1)

我认为问题是因为'startTime'大于'currentTime'。只做反向减法就可以了:

function updateClock() {
    var timeField = $(".timeSince");
    var currentTime = new Date();
    var difference = startTime - currentTime ;
    timeField.html(MillisecondsToDuration(difference));
    setTimeout(updateClock, 1000);
}

http://jsbin.com/ogomi3/edit

我不确定这是不是你想要的。