Since there are 3,600 seconds in an hour, the easiest way to convert seconds to hours is to divide by 3,600. For instance, 4,500 seconds divided by 3,600 is 1.25 hours. If you end up with a fraction of an hour and want to convert it into minutes, multiply the fraction by 60.
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);
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
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).
Format hh:mm:ss
console.log(display(60 * 60 * 2.5 + 25)) // 2.5 hours + 25 seconds
function display (seconds) {
const format = val => `0${Math.floor(val)}`.slice(-2)
const hours = seconds / 3600
const minutes = (seconds % 3600) / 60
return [hours, minutes, seconds % 60].map(format).join(':')
}
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
.
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
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.
function secondsToTime(e){
var 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
*/
You can also use native Date object:
var date = new Date(null);
date.setSeconds(timeInSeconds);
// retrieve time ignoring the browser timezone - returns hh:mm:ss
var utc = date.toUTCString();
// negative start index in substr does not work in IE 8 and earlier
var time = utc.substr(utc.indexOf(':') - 2, 8)
// retrieve each value individually - returns h:m:s
var time = date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds();
// does not work in IE8 and below - returns hh:mm:ss
var time = date.toISOString().substr(11, 8);
// not recommended - only if seconds number includes timezone difference
var time = date.toTimeString().substr(0, 8);
Of course this solution works only for timeInSeconds less than 24 hours ;)
function secondsToMinutes(time){
return Math.floor(time / 60)+':'+Math.floor(time % 60);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With