Javascript seconds to minutes and seconds
For people dropping in hoping for a quick simple and thus short solution to format seconds into M:SS
:
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
done..
The function accepts either a Number
(preferred) or a String
(2 conversion 'penalties' which you can halve by prepending +
in the function call's argument for s
as in: fmtMSS(+strSeconds)
), representing positive integer seconds s
as argument.
Examples:
fmtMSS( 0 ); // 0:00
fmtMSS( '8'); // 0:08
fmtMSS( 9 ); // 0:09
fmtMSS( '10'); // 0:10
fmtMSS( 59 ); // 0:59
fmtMSS( +'60'); // 1:00
fmtMSS( 69 ); // 1:09
fmtMSS( 3599 ); // 59:59
fmtMSS('3600'); // 60:00
fmtMSS('3661'); // 61:01
fmtMSS( 7425 ); // 123:45
Breakdown:
function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss
return( s - // take value s and subtract (will try to convert String to Number)
( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60
// (will also try to convert String to Number)
) / 60 + ( // and divide the resulting Number by 60
// (can never result in a fractional value = no need for rounding)
// to which we concatenate a String (converts the Number to String)
// who's reference is chosen by the conditional operator:
9 < s // if seconds is larger than 9
? ':' // then we don't need to prepend a zero
: ':0' // else we do need to prepend a zero
) + s ; // and we add Number s to the string (converting it to String as well)
}
Note: Negative range could be added by prepending (0>s?(s=-s,'-'):'')+
to the return expression (actually, (0>s?(s=-s,'-'):0)+
would work as well).
Another fancy solution:
function fancyTimeFormat(duration)
{
// Hours, minutes and seconds
var hrs = ~~(duration / 3600);
var mins = ~~((duration % 3600) / 60);
var secs = ~~duration % 60;
// Output like "1:01" or "4:03:59" or "123:03:59"
var ret = "";
if (hrs > 0) {
ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
}
ret += "" + mins + ":" + (secs < 10 ? "0" : "");
ret += "" + secs;
return ret;
}
~~
is a shorthand for Math.floor
, see this link for more info
Try online
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);
2020 UPDATE
Using basic math and simple javascript this can be done in just a few lines of code.
EXAMPLE - Convert 7735 seconds
to HH:MM:SS
.
MATH:
Calculations use:
Math.floor()
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
The
Math.floor()
function returns the largest integer less than or equal to a given number.
%
arithmetic operator (Remainder) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
Check out code below. Seconds are divided by 3600
to get number of hours and a remainder, which is used to calculate number of minutes and seconds.
HOURS => 7735 / 3600 = 2 remainder 535
MINUTES => 535 / 60 = 8 remainder 55
SECONDS => 55
LEADING ZEROS:
Many answers here use complicated methods to show number of hours, minutes and seconds in a proper way with leading zero - 45
, 04
etc. This can be done using padStart()
. This works for strings so the number must be converted to string using toString()
.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
The
padStart()
method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
CODE:
function secondsToTime(e){
const h = Math.floor(e / 3600).toString().padStart(2,'0'),
m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),
s = Math.floor(e % 60).toString().padStart(2,'0');
return h + ':' + m + ':' + s;
//return `${h}:${m}:${s}`;
}
console.log(secondsToTime(7735)); // 02:08:55
/*
secondsToTime(SECONDS) // HH:MM:SS
secondsToTime(8) // 00:00:08
secondsToTime(68) // 00:01:08
secondsToTime(1768) // 00:29:28
secondsToTime(3600) // 01:00:00
secondsToTime(5296) // 01:28:16
secondsToTime(7735) // 02:08:55
secondsToTime(45296) // 12:34:56
secondsToTime(145296) // 40:21:36
secondsToTime(1145296) // 318:08:16
*/