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');
Share:
395,756
Hannoun Yassir
Author by

Hannoun Yassir

Updated on July 08, 2022

Comments

  • Hannoun Yassir
    Hannoun Yassir almost 2 years

    How can I convert seconds to an HH-MM-SS string using JavaScript?

  • Ben
    Ben over 11 years
    That sounded good !After checking, it does not returns 03:00, but for any value entered, just 00:00.
  • Cleiton
    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
    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
    Dave Clark over 10 years
    Granted 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
    BT643 about 10 years
    There's some issues with this I think? When I tried it, I was getting decimals back, so 180 seconds would return 0.05 in the hours variable. I put it inside a parseInt 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
    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
    BT643 about 10 years
    Ah, 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
    T.J. Crowder about 10 years
    @BT643: totalSeconds % 60 can only have a fractional portion if totalSeconds 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 in minutes and seconds.)
  • Samrat Saha
    Samrat Saha about 10 years
    formatSeconds(3919); //Returns 01:05:19 Excellent Function .. Like it
  • Vitor Tyburski
    Vitor Tyburski almost 10 years
    This answer is, if anything, partially wrong. What happens if the amount exceeds 86400 seconds? ;)
  • Xavi Esteve
    Xavi Esteve over 9 years
    @HannounYassir console.log( hours +':'+ ('0'+minutes).slice(-2) +':'+ ('0'+seconds).slice(-2) );
  • Kris Khaira
    Kris Khaira over 9 years
    They 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
    jminardi about 9 years
    I don't know why everyone is adding extra libraries or doing the math manually when this works perfectly. Thanks!
  • Sheelpriy
    Sheelpriy over 8 years
    moreover ... if u want to do all date time thing easily.. use momentJS
  • Gilad Peleg
    Gilad Peleg over 8 years
    What happens if the number of seconds exceeds a day?
  • Frank
    Frank over 8 years
    This can even be shortened to one line: new Date(SECONDS * 1000).toISOString().substr(11, 8);
  • elquimista
    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
    Daniel Viglione almost 8 years
    I think the other solution is better than throwing another js library in the mix.
  • Riz
    Riz over 7 years
    Brilliant. Without any 3rd party lib. It's best
  • Renato Gama
    Renato Gama about 7 years
    The 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
    NibblyPig about 7 years
    This does not work for me in IE11, I get Object doesn't support property or method 'toISOString'
  • OrangePot
    OrangePot almost 7 years
    What happens if the number of seconds exceeds a year?
  • Mike Stoddart
    Mike Stoddart almost 7 years
    What about fractions of a second? 03:45:45.xxx?
  • Timothy Dalton
    Timothy Dalton almost 7 years
    As @renatoargh has stated, this solution can only be used for seconds less equal 24 hours, be careful otherwise.
  • Kimball
    Kimball almost 7 years
    Can you provide an expanded/reading version of your code as well so we can more easily see what is happening? Thanks.
  • David Callanan
    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
    StefansArya about 6 years
    Did you copy paste from this answer?
  • yan bellavance
    yan bellavance about 6 years
    looping 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
    yan bellavance about 6 years
    Just add this littel helper function: function pad_it(num, size) { var s = num+""; while (s.length < size) s = "0" + s; return s; }
  • madprops
    madprops about 6 years
    Could use default parameters like (input ,separator=":"). Also it didn't return anything until I modified it a bit paste.ee/p/FDNag
  • shaedrich
    shaedrich almost 6 years
    But this cannot be made optional. That might look ugly.
  • Ikrom
    Ikrom almost 6 years
    Uncaught TypeError: dt.addSeconds is not a function
  • kpull1
    kpull1 almost 6 years
    @Ikrom check the sample, I created a new one in jsfiddle since the old one returned 404 error
  • Ikrom
    Ikrom almost 6 years
    Looks like I didn't release that you were using custom method addSeconds on Date object like Date.prototype.addSeconds = function(seconds){...}. Yes, it works, thanks for the update.
  • Andrew
    Andrew almost 6 years
    This needs example input & example output.
  • Arlo
    Arlo over 5 years
    Thanks! no need to include a Library in a browser extension. Simple and works!
  • Maoritzio
    Maoritzio about 5 years
    although this is working, I keep getting the following error: ERROR RangeError: Invalid time value at Date.toISOString
  • Steven Spungin
    Steven Spungin almost 5 years
    If 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
    Stefnotch almost 5 years
    @SantiagoHernández Great! This now works perfectly for times over 24 hours.
  • yonatanmn
    yonatanmn almost 5 years
    for MM:SS -> ...substr(14, 5). I do this after checking if SECONDS < 3600
  • user1063287
    user1063287 almost 5 years
    secondsToTimeSpan(8991) returns 6.00:05:51 whereas i think it should return 00:02:29:51
  • John Slegers
    John Slegers almost 5 years
    @madprops : Actually, the version in my answer already sets : as default for the separator parameter, as I already explained. This is done by the statement typeof 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
    Andris almost 5 years
    Adding library for one simple action i think shouldn't be accepted answer. Yes, this works, but there is better solutions!!!
  • George Y.
    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
    Yuna about 4 years
    You can omit + "." + p.getMilliseconds() by just using new Date(p.getTime()-o.getTime()).toISOString().split("T")[1].sp‌​lit("Z")[0]
  • NVRM
    NVRM about 4 years
    Looks alright, yes your version it faster: See benchmark jsben.ch/4sQY1 Accepted edit! Thank you.
  • ashleedawg
    ashleedawg almost 4 years
    Using this library for one minor task like this adds 59,024 bytes to your project for the same effect that about 53 bytes will give you. . . From below: new Date(SECONDS * 1000).toISOString().substr(11, 8);
  • Accountant م
    Accountant م over 3 years
    This is the most correct answer because it doesn't overflow if more than 24 hours.
  • Maahi Bhat
    Maahi Bhat over 3 years
    great, but based on requirements if you need it or not
  • djvg
    djvg over 3 years
    From 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
    Supra_01 about 3 years
    I found this on the MDN docs and thought it might be helpful. let [hour, minute, second] = new Date().toLocaleTimeString("en-US").split(/:| /)
  • Matias
    Matias about 3 years
    It 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
    jrochkind almost 3 years
    As long as your number of hours doesn't go over... 24?
  • omarjebari
    omarjebari almost 3 years
    This 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
    PaulCrp over 2 years
    Like said before, this will overflow after 24 hours
  • NoxFly
    NoxFly over 2 years
    Nowadays, String.substr() is deprecated. Use String.slice() or String.substring instead.
  • Dawood Awan
    Dawood Awan about 2 years
    This is beautiful.
  • Izhaki
    Izhaki almost 2 years
    substr has been deprecated. Answer should probably be updated to use substring instead.
  • Cleiton
    Cleiton almost 2 years
    @Izhaki I updated.
  • Jamie Hutber
    Jamie Hutber almost 2 years
    But this doesn't display the seconds. Just the hours and minitues :/
  • Kappacake
    Kappacake almost 2 years
    substr is deprecated. Use substring(11, 19) or substring(14,19) instead