Coder Perfect

Is it possible to convert seconds to HH-MM-SS using JavaScript?

Problem

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

Asked by Hannoun Yassir

Solution #1

You may perform this without using an external JavaScript library by using the JavaScript Date method, as seen below:

var date = new Date(null);
date.setSeconds(SECONDS); // specify value for SECONDS here
var result = date.toISOString().substr(11, 8);

Or, as @Frank suggested, a one-liner:

new Date(SECONDS * 1000).toISOString().substr(11, 8);

Answered by Harish Anchu

Solution #2

Updated (2020):

Please consider using @Frank’s one-line solution:

new Date(SECONDS * 1000).toISOString().substr(11, 8)

If you want to show simply MM:SS and SECONDS3600, use the following code:

new Date(SECONDS * 1000).toISOString().substr(14, 5)

It is, without a doubt, the best option.

Old answer:

Take advantage of the Moment.js library.

Answered by Cleiton

Solution #3

Any built-in feature of the standard Date object, in my opinion, will not perform this for you in a more convenient way than doing the work yourself.

hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;

Example:

Answered by T.J. Crowder

Solution #4

I realize this is an old post, 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

Answered by Santiago Hernández

Solution #5

moment.js can be used for this, as Cleiton said in his response:

moment().startOf('day')
        .seconds(15457)
        .format('H:mm:ss');

Answered by Oliver Salzburg

Post is based on https://stackoverflow.com/questions/1322732/convert-seconds-to-hh-mm-ss-with-javascript