Basic Time Keeper

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
icesolid
Forum Regular
Posts: 502
Joined: Mon May 06, 2002 9:36 pm
Location: Buffalo, NY

Basic Time Keeper

Post 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
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Basic Time Keeper

Post 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?
icesolid
Forum Regular
Posts: 502
Joined: Mon May 06, 2002 9:36 pm
Location: Buffalo, NY

Re: Basic Time Keeper

Post by icesolid »

None at all. Thanks for the help!
Post Reply