Convert seconds to HH-MM-SS with JavaScript?
395,756
Solution 1
Updated (2020):
Please use @Frank's one line solution:
new Date(SECONDS * 1000).toISOString().substring(11, 16)
If SECONDS<3600 and if you want to show only MM:SS then use below code:
new Date(SECONDS * 1000).toISOString().substring(14, 19)
It is by far the best solution.
Old answer:
Use the Moment.js
library.
Solution 2
You can manage to do this without any external JavaScript library with the help of JavaScript Date method like following:
var date = new Date(null);
date.setSeconds(SECONDS); // specify value for SECONDS here
var result = date.toISOString().substr(11, 8);
Or, as per @Frank's comment; a one liner:
new Date(SECONDS * 1000).toISOString().substr(11, 8);
Solution 3
I don't think any built-in feature of the standard Date object will do this for you in a way that's more convenient than just doing the math yourself.
hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;
Example:
let totalSeconds = 28565;
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let seconds = totalSeconds % 60;
console.log("hours: " + hours);
console.log("minutes: " + minutes);
console.log("seconds: " + seconds);
// If you want strings with leading zeroes:
minutes = String(minutes).padStart(2, "0");
hours = String(hours).padStart(2, "0");
seconds = String(seconds).padStart(2, "0");
console.log(hours + ":" + minutes + ":" + seconds);
Solution 4
I know this is kinda old, but...
ES2015:
var toHHMMSS = (secs) => {
var sec_num = parseInt(secs, 10)
var hours = Math.floor(sec_num / 3600)
var minutes = Math.floor(sec_num / 60) % 60
var seconds = sec_num % 60
return [hours,minutes,seconds]
.map(v => v < 10 ? "0" + v : v)
.filter((v,i) => v !== "00" || i > 0)
.join(":")
}
It will output:
toHHMMSS(129600) // 36:00:00
toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18
Solution 5
As Cleiton pointed out in his answer, moment.js can be used for this:
moment().startOf('day')
.seconds(15457)
.format('H:mm:ss');
Author by
Hannoun Yassir
Updated on July 08, 2022Comments
-
Hannoun Yassir almost 2 years
How can I convert seconds to an
HH-MM-SS
string using JavaScript? -
Ben over 11 yearsThat sounded good !After checking, it does not returns 03:00, but for any value entered, just 00:00.
-
Cleiton over 11 years@J.J. Crowder, you are right. But this answer was given on 2009, that time it was a good ideia. I updated my answer.
-
Hamish Grubijan about 11 years@Cleiton, your updated answer is not full. I tried it as is and got:
TypeError: Object [object Date] has no method 'clearTime'
. -
Dave Clark over 10 yearsGranted Moment.js isn't all that big but if all you're doing with it is to convert seconds to hh:mm:ss, it seems like a bit of overkill. Rather use one of the functions suggested in these or other answers.
-
BT643 about 10 yearsThere's some issues with this I think? When I tried it, I was getting decimals back, so 180 seconds would return
0.05
in thehours
variable. I put it inside aparseInt
which fixed it for my case, but I don't think that'd be accurate for everything. Still, this helped me, so thanks! -
T.J. Crowder about 10 years@BT643: Odd that I didn't handle that. I've done so now, you don't want to use
parseInt
for it, that's for parsing strings, not manipulating numbers.Math.floor
would be the relevant operation here. -
BT643 about 10 yearsAh, ok! Changed my code. Although you do probably want it on the seconds as well:
seconds = Math.floor(totalSeconds % 60);
. I just got a decimal result there too. -
T.J. Crowder about 10 years@BT643:
totalSeconds % 60
can only have a fractional portion iftotalSeconds
has a fractional portion. Whether you want to floor it will depend on whether you want to lose that information or retain it. (The other floor operations we're doing don't lose any information, because they're just clearing out the data that will end up inminutes
andseconds
.) -
Samrat Saha about 10 yearsformatSeconds(3919); //Returns 01:05:19 Excellent Function .. Like it
-
Vitor Tyburski almost 10 yearsThis answer is, if anything, partially wrong. What happens if the amount exceeds 86400 seconds? ;)
-
Xavi Esteve over 9 years@HannounYassir
console.log( hours +':'+ ('0'+minutes).slice(-2) +':'+ ('0'+seconds).slice(-2) );
-
Kris Khaira over 9 yearsThey might have changed their API. I've updated the code (it's 2 years too late and you probably moved on, but I thought others might find it useful).
-
jminardi about 9 yearsI don't know why everyone is adding extra libraries or doing the math manually when this works perfectly. Thanks!
-
Sheelpriy over 8 yearsmoreover ... if u want to do all date time thing easily.. use momentJS
-
Gilad Peleg over 8 yearsWhat happens if the number of seconds exceeds a day?
-
Frank over 8 yearsThis can even be shortened to one line:
new Date(SECONDS * 1000).toISOString().substr(11, 8);
-
elquimista about 8 years@GiladPeleg if the number of seconds exceeds a day, number of days is calculated internally and it will only return the remaining hours, minutes and seconds. If you want to count number of days as well, you can try
moment().startOf('year').seconds(30000000).format('DDD HH:mm:ss')
. -
Daniel Viglione almost 8 yearsI think the other solution is better than throwing another js library in the mix.
-
Riz over 7 yearsBrilliant. Without any 3rd party lib. It's best
-
Renato Gama about 7 yearsThe problem with this approach is that it will overflow after 24 hours, preventing you from showing more than this length of time. Perfect solution if you have less than 24 hours in seconds.
-
NibblyPig about 7 yearsThis does not work for me in IE11, I get
Object doesn't support property or method 'toISOString'
-
OrangePot almost 7 yearsWhat happens if the number of seconds exceeds a year?
-
Mike Stoddart almost 7 yearsWhat about fractions of a second? 03:45:45.xxx?
-
Timothy Dalton almost 7 yearsAs @renatoargh has stated, this solution can only be used for seconds less equal 24 hours, be careful otherwise.
-
Kimball almost 7 yearsCan you provide an expanded/reading version of your code as well so we can more easily see what is happening? Thanks.
-
David Callanan over 6 years@OrangePot if the number of seconds exceeds a year, number of years is calculated internally and it will only return the remaining days, hours, minutes and seconds. If you want to count number of years as well, you can try
.format('YYYY DDD HH:mm:ss')
-
StefansArya about 6 yearsDid you copy paste from this answer?
-
yan bellavance about 6 yearslooping results is a very bad coding technique and should never be used it will hog your processing power and give you a laggy site
-
yan bellavance about 6 yearsJust add this littel helper function: function pad_it(num, size) { var s = num+""; while (s.length < size) s = "0" + s; return s; }
-
madprops about 6 yearsCould use default parameters like (input ,separator=":"). Also it didn't return anything until I modified it a bit paste.ee/p/FDNag
-
shaedrich almost 6 yearsBut this cannot be made optional. That might look ugly.
-
Ikrom almost 6 yearsUncaught TypeError: dt.addSeconds is not a function
-
kpull1 almost 6 years@Ikrom check the sample, I created a new one in jsfiddle since the old one returned 404 error
-
Ikrom almost 6 yearsLooks like I didn't release that you were using custom method
addSeconds
on Date object likeDate.prototype.addSeconds = function(seconds){...}
. Yes, it works, thanks for the update. -
Andrew almost 6 yearsThis needs example input & example output.
-
Arlo over 5 yearsThanks! no need to include a Library in a browser extension. Simple and works!
-
Maoritzio about 5 yearsalthough this is working, I keep getting the following error:
ERROR RangeError: Invalid time value at Date.toISOString
-
Steven Spungin almost 5 yearsIf you modulus the seconds using the number of seconds in a day, this works for times >= 1 day.
new Date(printTime % (60 * 60 * 24)) * 1000).toISOString().substr(11, 8)
. -
Stefnotch almost 5 years@SantiagoHernández Great! This now works perfectly for times over 24 hours.
-
yonatanmn almost 5 yearsfor
MM:SS
->...substr(14, 5)
. I do this after checking ifSECONDS < 3600
-
user1063287 almost 5 years
secondsToTimeSpan(8991)
returns6.00:05:51
whereas i think it should return00:02:29:51
-
John Slegers almost 5 years@madprops : Actually, the version in my answer already sets
:
as default for theseparator
parameter, as I already explained. This is done by the statementtypeof separator !== 'undefined' ? separator : ':'
. Also, your function is pretty much identical to mine save some cosmetic changes and they should both produce the same output... except my version has much better browser support. Yours won't work in ANY version of Internet Explorer or MS Edge < 14. -
Andris almost 5 yearsAdding library for one simple action i think shouldn't be accepted answer. Yes, this works, but there is better solutions!!!
-
George Y. almost 5 years+1. This or the T.J. should be the accepted answer, as those are the only ones which work for situations when duration exceeds 24 hours (and the question doesn't limit duration).
-
Yuna about 4 yearsYou can omit
+ "." + p.getMilliseconds()
by just usingnew Date(p.getTime()-o.getTime()).toISOString().split("T")[1].split("Z")[0]
-
NVRM about 4 yearsLooks alright, yes your version it faster: See benchmark jsben.ch/4sQY1 Accepted edit! Thank you.
-
ashleedawg almost 4 yearsUsing this library for one minor task like this adds
59,024 bytes
to your project for the same effect that about53 bytes
will give you. . . From below:new Date(SECONDS * 1000).toISOString().substr(11, 8);
-
Accountant م over 3 yearsThis is the most correct answer because it doesn't overflow if more than 24 hours.
-
Maahi Bhat over 3 yearsgreat, but based on requirements if you need it or not
-
djvg over 3 yearsFrom mozilla: "The
toISOString()
method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ
or±YYYYYY-MM-DDTHH:mm:ss.sssZ
, respectively)." -
Supra_01 about 3 yearsI found this on the MDN docs and thought it might be helpful.
let [hour, minute, second] = new Date().toLocaleTimeString("en-US").split(/:| /)
-
Matias about 3 yearsIt is fine to do "new Date" every second? (considering I´m printing a clock) or is it better to reuse date variable and just change seconds every time?
-
jrochkind almost 3 yearsAs long as your number of hours doesn't go over... 24?
-
omarjebari almost 3 yearsThis is plain wrong! As others have pointed put if you have more than a day's worth of secods the answer is incorrect. USE WITH CAUTION! See Santiago Hernández's answer below.
-
PaulCrp over 2 yearsLike said before, this will overflow after 24 hours
-
NoxFly over 2 yearsNowadays, String.substr() is deprecated. Use String.slice() or String.substring instead.
-
Dawood Awan about 2 yearsThis is beautiful.
-
Izhaki almost 2 years
substr
has been deprecated. Answer should probably be updated to usesubstring
instead. -
Cleiton almost 2 years@Izhaki I updated.
-
Jamie Hutber almost 2 yearsBut this doesn't display the seconds. Just the hours and minitues :/
-
Kappacake almost 2 years
substr
is deprecated. Usesubstring(11, 19)
orsubstring(14,19)
instead