Page 1 of 1

Basic Time Keeper

Posted: Thu Oct 29, 2009 11:38 am
by icesolid
I have a simple script that increments every second and displays the total. Is it possible in JavaScript to just take that whole number and format it into time like hh:ii:ss?

Code: Select all

<script type="text/javascript">
var count = 0;
 
setTimeout('calculate_count();', 1000);
 
function calculate_count() {
    count++;
    document.getElementById('count').value = count;
    setTimeout('calculate_count();', 1000);
}
</script>
<input type="text" id="count" value="0" />
Example format the number 120 into 00:02:00

Re: Basic Time Keeper

Posted: Thu Oct 29, 2009 1:27 pm
by kaszu
Yes it is

Code: Select all

function formatTime (seconds) {
    //~~ does the same as Math.floor()
    //Get full hours
    var hours = ~~(seconds/3600);
    //Get reminding seconds without hours
    seconds = seconds % 3600;
 
    //Same with minutes
    var minutes = ~~(seconds/60);
    seconds = seconds % 60;
 
    //will use _f for formatting to convert 2 => 02, 12 => 12, etc.
    //since we need 01:10:06 not 1:10:6
    function _f (t) {
        return (t < 10 ? '0' + t : t);
    }
 
    //Return hh:ii:ss
    return _f(hours) + ':' + _f(minutes) + ':' + _f(seconds);
}
Questions?

Re: Basic Time Keeper

Posted: Thu Oct 29, 2009 2:06 pm
by icesolid
None at all. Thanks for the help!