James Moore James Moore - 5 months ago 29
Javascript Question

Javascript seconds to minutes and seconds

This is a common problem but I'm not sure how to solve it. The code below works fine.

var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);

var secd = mind % 60;
var seconds = Math.ceil(secd);


However, when I get to 1 hour or 3600 seconds it returns 0 minutes and 0 seconds. How can I avoid this so it returns all the minutes?

Thanks

Answer

You’re doing it wrong. To get the number of full minutes, divide the number of total seconds by 60 (60 seconds/minute):

var minutes = Math.floor(time / 60);

And to get the remaining seconds, multiply the full minutes with 60 and subtract from the total seconds:

var seconds = time - minutes * 60;

Now if you also want to get the full hours too, divide the number of total seconds by 3600 (60 minutes/hour · 60 seconds/minute) first, then calculate the remaining seconds:

var hours = Math.floor(time / 3600);
time = time - hours * 3600;

Then you calculate the full minutes and remaining seconds.

Bonus:

Use the following code to pretty-print the time (suggested by Dru)

function str_pad_left(string,pad,length) {
    return (new Array(length+1).join(pad)+string).slice(-length);
}

var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);
Comments