Javascript seconds to minutes and seconds
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
21 Answers
21
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);
It's a bit cleaner to get remaining seconds by doing 'var seconds = time % 60'.
– Edward D'Souza
Dec 8 '11 at 15:20
@Radio add leading zeros using
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);
– Dru
Dec 6 '12 at 7:20
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);
This solution won't work for negative values of
time
. If you for instance input -1 seconds, you get -1minute and 59 seconds back...– Pylinux
Oct 20 '13 at 18:10
time
What's the sense of having negative
time
? Logically a time difference is always positive– mcont
Dec 29 '14 at 19:08
time
You can use modulus to get the number of seconds, it's more readable in my opinion.
var seconds = time % 60
– JCM
Jun 10 '16 at 19:27
var seconds = time % 60
Another fancy solution:
function fancyTimeFormat(time)
// Hours, minutes and seconds
var hrs = ~~(time / 3600);
var mins = ~~((time % 3600) / 60);
var secs = ~~time % 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
~~
Math.floor
This solution also works for negative values of
time
– Pylinux
Oct 20 '13 at 18:06
time
What's the meaning of
~~
?– mcont
Dec 29 '14 at 19:03
~~
It's a basic shorhand for
Math.floor
, see this link.– lapin
May 20 '15 at 11:10
Math.floor
Its work fine..... :) You can round the value like this way hrs = hrs.toFixed(0); mins = mins.toFixed(0); secs = secs.toFixed(0);
– Ayaat Shifa
Jun 25 '15 at 7:50
Thanks for this solution! I added
time = math.round(time)
to the first line to give me rounded seconds.– fotoflo
Feb 6 at 0:53
time = math.round(time)
For people dropping in hoping for a quick simple and thus short solution to format seconds into M:SS
:
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.
Number
String
+
s
fmtMSS(+strSeconds)
s
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).
(0>s?(s=-s,'-'):'')+
(0>s?(s=-s,'-'):0)+
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 ;)
Hadn't thought of letting the Date object handle the formatting. Less flexible, but if you want hh:mm:ss (or a subsection of that) this is great
– MartinAnsty
May 2 '12 at 21:51
I tried this with 25 seconds and it returned 01:00:25 which equates to 1 hour and 25 seconds.
– timstermatic
Aug 19 '13 at 12:32
Yes, probably because of your timezone. I have updated the solution to handle this case.
– hamczu
Aug 21 '13 at 11:45
date
could also be constructed as var date = new Date(timeInSeconds * 1000)
– Nuno André
Nov 25 '17 at 9:27
date
var date = new Date(timeInSeconds * 1000)
To add leading zeros, I would just do:
var minutes = "0" + Math.floor(time / 60);
var seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);
Nice and short
function secondsToMinutes(time)
return Math.floor(time / 60)+':'+Math.floor(time % 60);
This can be improved with zero padding the seconds:
function secondsToMinutes(time) return Math.floor(0 / 60)+':'+('0'+Math.floor(0 % 60)).slice(-2);
– Kus
Dec 7 '17 at 6:00
function secondsToMinutes(time) return Math.floor(0 / 60)+':'+('0'+Math.floor(0 % 60)).slice(-2);
nice! thank you @Kus. Just you might want to replace those two
0
s with time
, am I correct?– mikey
Feb 19 at 23:20
0
time
@mikey oops! Yes,
function secondsToMinutes(time) return Math.floor(time / 60) + ':' + ('0' + Math.floor(time % 60)).slice(-2)
– Kus
Feb 21 at 22:38
function secondsToMinutes(time) return Math.floor(time / 60) + ':' + ('0' + Math.floor(time % 60)).slice(-2)
A one liner (doesnt work with hours):
function sectostr(time)
return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
Seconds to h:mm:ss
var hours = Math.floor(time / 3600);
time -= hours * 3600;
var minutes = Math.floor(time / 60);
time -= minutes * 60;
var seconds = parseInt(time % 60, 10);
console.log(hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds));
Another but much more elegant solution for this is as follows:
/**
* Convert number secs to display time
*
* 65 input becomes 01:05.
*
* @param Number inputSeconds Seconds input.
*/
export const toMMSS = inputSeconds =>
const secs = parseInt( inputSeconds, 10 );
let minutes = Math.floor( secs / 60 );
let seconds = secs - minutes * 60;
if ( 10 > minutes )
minutes = '0' + minutes;
if ( 10 > seconds )
seconds = '0' + seconds;
// Return display.
return minutes + ':' + seconds;
;
2018 best variant
Format hh:mm:ss
hh:mm:ss
console.log(display(60 * 60 * 2.5 + 25)) // 2.5 hours + 25 seconds
function display (seconds)
const hours = seconds / 3600
const minutes = (seconds % 3600) / 60
seconds %= 60
return [hours, minutes, seconds].map(format).join(':')
function format (val)
return ('0' + Math.floor(val)).slice(-2)
For adding zeros I really don't see the need to have a full other function where you can simply use for example
var mins=Math.floor(StrTime/60);
var secs=StrTime-mins * 60;
var hrs=Math.floor(StrTime / 3600);
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs);
Its why we have conditional statements in the first place.
(condition?if true:if false) so if example seconds is more than 9 than just show seconds else add a string 0 before it.
The Following function will help you to get Days , Hours , Minutes , seconds
toDDHHMMSS(inputSeconds)
const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
let ddhhmmss = '';
if (Days > 0)
ddhhmmss += Days + ' Day ';
if (Hour > 0)
ddhhmmss += Hour + ' Hour ';
if (Minutes > 0)
ddhhmmss += Minutes + ' Minutes ';
if (Seconds > 0)
ddhhmmss += Seconds + ' Seconds ';
return ddhhmmss;
alert( toDDHHMMSS(2000));
You've done enough code to track minutes and seconds portions of time.
What you could do is add the hours factor in:
var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);
var mind = hrd % 60;
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
var moreminutes = minutes + hours * 60
This would give you what you need also.
I tried this using "time" as seconds and it didn't work. For example, 975 sec means hrd = 975, which means hours is 16.
– Spedge
Sep 11 '13 at 10:28
I was thinking of a faster way to get this done and this is what i came up with
var sec = parseInt(time);
var min=0;
while(sec>59) sec-=60; min++;
If we want to convert "time" to minutes and seconds, for example:
// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59) sec-=60; min++; //sec = 15; min = 1
I suggest another solution:
function formatTime(nbSeconds, hasHours) 0)) * s) / 60;
time.push(format(Math.floor(calc)));//minute
calc = (calc - (time[time.length-1])) * 60;
time.push(format(Math.round(calc)));//second
function format(n) //it makes "0X"/"00"/"XX"
return (("" + n) / 10).toFixed(1).replace(".", "");
//if (!hasHours) time.shift();//you can set only "min: sec"
return time.join(":");
;
console.log(formatTime(3500));//58:20
console.log(formatTime(305));//05:05
console.log(formatTime(75609, true));//21:00:09
console.log(formatTime(0, true));//00:00:00
I know it has been solved in many ways. I needed this function for an After Effects script, where speed or namespace pollution is not an issue. I drop it here for someone that needs something similar. I also wrote some tests and worked fine. So here's the code:
Number.prototype.asTime = function ()
var hour = Math.floor(this / 3600),
min = Math.floor((this - hour * 3600) / 60),
sec = this - hour * 3600 - min * 60,
hourStr, minStr, secStr;
if(hour)
hourStr = hour.toString(),
minStr = min < 9 ? "0" + min.toString() : min.toString();
secStr = sec < 9 ? "0" + sec.toString() : sec.toString();
return hourStr + ":" + minStr + ":" + secStr + "hrs";
if(min)
minStr = min.toString();
secStr = sec < 9 ? "0" + sec.toString() : sec.toString();
return minStr + ":" + secStr + "min";
return sec.toString() + "sec";
Put my two cents in :
function convertSecondsToMinutesAndSeconds(seconds)
var minutes;
var seconds;
minutes = Math.floor(seconds/60);
seconds = seconds%60;
return [minutes, seconds];
So this :
var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);
Will have the following output :
[1,41];
Then you can print it like so :
console.log('TIME : ' + minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');
//TIME : 1 minutes, 41 seconds
try this :
Converting Second to HOURS, MIN and SEC.
function convertTime(sec)
var hours = Math.floor(sec/3600);
(hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
var min = Math.floor(sec/60);
(min >= 1) ? sec = sec - (min*60) : min = '00';
(sec < 1) ? sec='00' : void 0;
(min.toString().length == 1) ? min = '0'+min : void 0;
(sec.toString().length == 1) ? sec = '0'+sec : void 0;
return hours+':'+min+':'+sec;
strftime.js (strftime github) is one of the best time formatting libraries. It's extremely light - 30KB - and effective. Using it you can convert seconds into time easily in one line of code, relying mostly on the native Date class.
When creating a new Date, each optional argument is positional as follows:
new Date(year, month, day, hours, minutes, seconds, milliseconds);
So if you initialize a new Date with all arguments as zero up to the seconds, you'll get:
var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)
You can see that 150 seconds is 2-minutes and 30-seconds, as seen in the date created. Then using an strftime format ("%M:%S" for "MM:SS"), it will output your minutes' string.
var mm_ss_str = strftime("%M:%S", date);
=> "02:30"
In one line, it would look like:
var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"
Plus this would allow you to interchangeable support HH:MM:SS and MM:SS based on the number of seconds. For example:
# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"
# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"
And of course, you can simply pass whatever format you want to strftime if you want the time string to be more or less semantic.
var format = 'Honey, you said you'd be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"
Hope this helps.
export function TrainingTime(props)
const train_time = props;
const hours = Math.floor(train_time/3600);
const minutes = Math.floor((train_time-hours * 3600) / 60);
const seconds = Math.floor((train_time%60));
return `$hours hrs $minutes min $seconds sec`;
Add some explanation to your code.
– Phil Roggenbuck
Aug 30 at 7:43
Welcome to Stack Overflow. As suggested by @PhilRoggenbuck, an explanation would help. For more info read stackoverflow.com/help/how-to-answer
– Mikkel
Aug 30 at 8:52
var seconds = 60;
var measuredTime = new Date(null);
measuredTime.setSeconds(seconds); // specify value of SECONDS
var Time = measuredTime.toISOString().substr(11, 8);
document.getElementById("id1").value = Time;
<div class="form-group">
<label for="course" class="col-md-4">Time</label>
<div class="col-md-8">
<input type="text" class="form-control" id="id1" name="field">Min
</div>
</div>
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thats because when time = 3600, 3600%3600 is always 0...so everything else will be 0 according to your calculation.
– MSI
Sep 17 '10 at 6:59