Convert seconds to hours, minutes and seconds (JavaScript)

This is JavaScript implementation of the PHP function previously described in Convert seconds to hours, minutes and seconds (PHP). Please see the link for more detailed explanation of the function.

  1. /**
  2.  * Convert number of seconds into time object
  3.  *
  4.  * @param integer secs Number of seconds to convert
  5.  * @return object
  6.  */
  7. function secondsToTime(secs)
  8. {
  9.     var hours = Math.floor(secs / (60 * 60));
  10.    
  11.     var divisor_for_minutes = secs % (60 * 60);
  12.     var minutes = Math.floor(divisor_for_minutes / 60);
  13.  
  14.     var divisor_for_seconds = divisor_for_minutes % 60;
  15.     var seconds = Math.ceil(divisor_for_seconds);
  16.    
  17.     var obj = {
  18.         "h": hours,
  19.         "m": minutes,
  20.         "s": seconds
  21.     };
  22.     return obj;
  23. }

Comments
1
great code man...
 :-)
Karan Saini, August 19th 2010, 15:31
2
looks nice but there're a lot of mistakes i.e. if i put 60s in i get 60s out instead of 1 minute...
deed, September 21st 2010, 12:02
3
I tested it and got the following results:

secondsToTime(50);
{"h": 0, "m": 0, "s": 50}
secondsToTime(60);
{"h": 0, "m": 1, "s": 0}
Are you sure you are passing "60" and not "60s"? It has to be an integer. If you want the function to typecast "secs" to an integer, simply add
secs = parseInt(secs, 10);
as the first line in it.
Andris, October 6th 2010, 16:56
4

// Outputs 24:05, 1:00:32
function rectime(secs) {
	var hr = Math.floor(secs / 3600);
	var min = Math.floor((secs - (hr * 3600))/60);
	var sec = secs - (hr * 3600) - (min * 60);
	
	while (min.length < 2) {min = '0' + min;}
	while (sec.length < 2) {sec = '0' + min;}
	if (hr) hr += ':';
	return hr + min + ':' + sec;
}
SmarT, March 13th 2011, 4:15
5
Sorry, rushed, here is corrected version:

function rectime(sec) {
	var hr = Math.floor(sec / 3600);
	var min = Math.floor((sec - (hr * 3600))/60);
	sec -= ((hr * 3600) + (min * 60));
	sec += ''; min += '';
	while (min.length < 2) {min = '0' + min;}
	while (sec.length < 2) {sec = '0' + sec;}
	hr = (hr)?':'+hr:'';
	return hr + min + ':' + sec;
}
SmarT, March 13th 2011, 4:24
6
hr = (hr)?hr+':':'';
:)
SmarT, March 13th 2011, 19:41
7
nice one smart work wonderfully
rayer, June 14th 2011, 7:08
8
next time: jsfiddle.net ;)
T, June 21st 2011, 6:28
9
I have modified a bit
function rectime(secs) {
	var hr = Math.floor(secs / 3600);
	var min = Math.floor((secs - (hr * 3600))/60);
	var sec = secs - (hr * 3600) - (min * 60);
	
	if (hr < 10) {hr = "0" + hr; }
	if (min < 10) {min = "0" + min;}
	if (sec < 10) {sec = "0" + sec;}
	if (hr) {hr = "00";}
	return hr + ':' + min + ':' + sec;
}
Doan Duc, August 1st 2011, 9:43
10
Why display seconds like 58.12183728392 ????

You correctly use Math.floor() everywhere EXCEPT where you should: var sec.
Guest, August 16th 2011, 15:46
11
Added a string formatter option:


function formatSecondsAsTime(secs, format) {
  var hr  = Math.floor(secs / 3600);
  var min = Math.floor((secs - (hr * 3600))/60);
  var sec = Math.floor(secs - (hr * 3600) -  (min * 60));

  if (hr < 10)   { hr    = "0" + hr; }
  if (min < 10) { min = "0" + min; }
  if (sec < 10)  { sec  = "0" + sec; }
  if (hr)            { hr   = "00"; }

  if (format != null) {
    var formatted_time = format.replace('hh', hr);
    formatted_time = formatted_time.replace('h', hr*1+""); // check for single hour formatting
    formatted_time = formatted_time.replace('mm', min);
    formatted_time = formatted_time.replace('m', min*1+""); // check for single minute formatting
    formatted_time = formatted_time.replace('ss', sec);
    formatted_time = formatted_time.replace('s', sec*1+""); // check for single second formatting
    return formatted_time;
  } else {
    return hr + ':' + min + ':' + sec;
  }
}
V, September 23rd 2011, 16:13
12
thank you :)
nong, January 5th 2012, 12:17
13
thank you very much for help.
Raju Rajotia Jangid, January 18th 2012, 9:21
14
I am a newbie who is still learning js and I have a question about the code that should help me learn something. 

This question is referencing the code posted by "V" on 9/23/2011

I believe you that it is the correct thing to do, but I do not understand why we are doing the line

 if (hr)            { hr   = "00"; } 

I read on w3schools.com:


If the Boolean object has no initial value, or if the passed value is one of the following:

    0
    -0
    null
    ""
    false
    undefined
    NaN

the object is set to false. For any other value it is set to true (even with the string "false")


So what I take away from that is "hr" has a value say two '2' then it would be changed to "00".  I would think we would want to replace a value like 0 or undefined with "00" but if I understand  w3schools,  if the hr was 0 or undefined   the object is  false" that would lead me to think I should use 

if (!hr)


but that is clearly not the case.  So I think I either miss-understand how that works or I do not understand why we are actually doing:
 if (hr)            { hr   = "00"; } 

Can someone who understands the code explain this?  Thank you for helping me learn :)
AndyS, April 7th 2012, 2:39
15
@AndyS - you're right. The hr in V's code will always change to "00" if it's not empty. So, like you said, if it's a number from 1-24, it will get changed to "00".

I don't think is needed at all, to be honest. All values below 10 will have a zero prepended anyway, which will automatically apply to "0".  The function should work just fine without the 'if'.
Andris, April 11th 2012, 15:21
16
This comment has been deleted
MarekK, June 26th 2012, 10:13
17
Something strange happend and it placed my friend address. OMG.
Here is my code:

//var txt = dhms(1234567, 'd:hh:mm:ss'); //example

function dhms(s, f) { // seconds, format
  var d=h=m=0;
  switch (true) {
  case (s>86400):
    d=Math.floor(s/86400);
    s-=d*86400;
  case (s>3600):
    h=Math.floor(s/3600);
    s-=h*3600;
  case (s>60):
    m=Math.floor(s/60);
    s-=m*60;
  } 
  if (f != null) {
    var f = f.replace('dd', (d<10)?"0"+d:d);
    f = f.replace('d', d);
    f = f.replace('hh', (h<10)?"0"+h:h);
    f = f.replace('h', h);
    f = f.replace('mm', (m<10)?"0"+m:m);
    f = f.replace('m', m);
    f = f.replace('ss', (s<10)?"0"+s:s);
    f = f.replace('s', s);
  } 
  else {
    f = d + ':' + h + ':' + m + ':' + s;
  }
}
MarekK, June 26th 2012, 10:17
18
I have found little mistake.

//var txt = dhms(1234567, 'd:hh:mm:ss'); //example

function dhms(s, f) { // seconds, format
  var d=h=m=0;
  switch (true) {
  case (s>86400):
    d=Math.floor(s/86400);
    s-=d*86400;
  case (s>3600):
    h=Math.floor(s/3600);
    s-=h*3600;
  case (s>60):
    m=Math.floor(s/60);
    s-=m*60;
  } 
  if (f != null) {
    var f = f.replace('dd', (d<10)?"0"+d:d);
    f = f.replace('d', d);
    f = f.replace('hh', (h<10)?"0"+h:h);
    f = f.replace('h', h);
    f = f.replace('mm', (m<10)?"0"+m:m);
    f = f.replace('m', m);
    f = f.replace('ss', (s<10)?"0"+s:s);
    f = f.replace('s', s);
  } 
  else {
    f = d + ':' + h + ':' + m + ':' + s;
  }
  return f; // :) omg...
}
MarekK, June 26th 2012, 11:43
19
And...
this also works well:
(part of above code)

  switch (true) {
  case (s>86400):
    d=Math.floor(s/86400);
    s%=86400;
  case (s>3600):
    h=Math.floor(s/3600);
    s%=3600;
  case (s>60):
    m=Math.floor(s/60);
    s%=60;
  } 

Here JavaScript Development Environment 2.0.1 you can test codes.
MarekK, June 26th 2012, 11:47
20
Can anyone post the opossitfor example i want to convert
5:35:26 (5hours, 35minutes, 26seconds) into 3 variables each time i call it
Akexander, August 21st 2012, 4:56
21
function secondsToTime(s){
    var h  = Math.floor( s / ( 60 * 60 ) );
        s -= h * ( 60 * 60 );
    var m  = Math.floor( s / 60 );
        s -= m * 60;
   
    return {
        "h": h,
        "m": m,
        "s": s
    };
}
Tarsus, October 10th 2012, 12:58
22
Can you send me full code..
i want a code for convert minute to hours 
like 1204.24 minute and result display 20 Hrs : 4.24 Min
ashok, July 19th 2013, 17:14
23
hey ,
i have one query 
if the code is in string like,
" 30min, 27sec" then it is not taking min as a min value i want reasult like i want the final reasult in total seconds. 
pls help me asap i need to submit in one hour
isha, August 30th 2013, 15:30
24
I know it's too late now but what you need is a totally different function. The function I supplied converts a number into an object, you on the other hand (if I understand correctly) need a function that converts a string to an object.

Sounds like a trivial task, you just need to do a little research. Best of luck with your task!
Andris, August 30th 2013, 21:03
25
Thanks for the code. Simple and efficient, just how we like things to be.
Added the number of days handling.
Cheers
krapaglok, October 28th 2013, 15:26
26
hele goeie site! thx :)
ruchir, November 1st 2013, 10:54
Name
Email (required)
will not be published
Website
Recaptcha
you will only be required to fill it in once in this session

You can use [code][/code] tags in your comments