Damon
Damon

Reputation: 75

Formatting Countup Timer Javascript

I am using the following code to display a count up clock The Minutes and Seconds are formatting fine, but Hours are being show as a negative number eg "-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>

Upvotes: 0

Views: 835

Answers (1)

Fran Verona
Fran Verona

Reputation: 5476

I think that the problem is because of 'startTime' is greater than 'currentTime'. Just doing the inverse substraction works fine:

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

I'm not sure if this is what you want.

Upvotes: 1

Related Questions