How to convert text time to mintes and seconds?

How would you convert the time into mintues and seconds?
When I click on the start button the time appears at 300 not 5:00 mintues.
How would you do this?

<!DOCTYPE html>
<html>
<head>
<title>TImer</title>
<script type="text/javascript">
    
    var COUNT = 60*5;
    
    var time, count;
    
    function display() {
        // displays time in span
        document.getElementById('timespan').innerHTML = count;
    };
    
    function countdown() {
        // starts countdown
        cddisplay();
        if (count == 0) {
            // time is up
        } else {
            count--;
            time = setTimeout("countdown()", 1000);
        }
    };
    
    function pause() {
        // pauses countdown
        clearTimeout(time);
    };
    
    function reset() {
        // resets countdown
        pause();
        count = COUNT;
        display();
    };
    
</script>

<body onload="reset()">
<span id="timespan"></span>
<input type="button" value="Start" onclick="countdown()">
<input type="button" value="Stop" onclick="pause()">
<input type="button" value="Reset" onclick="reset()">
</body>

</html>

A quick and dirty way would be to divide by 60, integer of that is the minute value, multiply that integer back by sixty and subtract it from the original count for the remaining seconds, or get the seconds from the modulo of the count and sixty.

So how would that look?

Depends on how you format it - you’d need to format the seconds part to have a leading zero if they’re below ten, but it’s probably quite easy.

I’m sure there’s probably a time formatting function out there, though.

Pseudo-code:

mn = int (count / 60)
sec = count - (mn * 60)

Not sure about JS syntax, so I’ll leave that to you.

	var mn = (count / 60);
	var sec = count - (mn * 60);

I have created varibles above, but I don’t know where the mn and sec should be used in the code.

This is what I added to the code to the first original post at the beginning.

	var mn = (count / 60);
	var sec = count - (mn * 60);    
    function cddisplay() {
        // displays time in span
        document.getElementById('timespan').innerHTML = mn + ':' + ((sec>9)?'':'0') + sec;
    };

But it doesn’t work so I have know idea what I’m doing wrong.

Another way would be to create a Date object, which provides methods to get the minutes and seconds (among others):

function display () {
  var date = new Date(count * 1000)
  var timeString = date.getMinutes() + ':' + date.getSeconds()
  
  document.getElementById('timespan').textContent = timeString
}

(whoops, x-post)

1 Like

when the time goes down it shows 5:0 how do you get 5:00?

Its fine I figured it out :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.