31

Possible Duplicate:
convert seconds to HH-MM-SS with javascript ?

Hi,

I have a float of 16.4534, which is the seconds of a duration of a video. I want to convert this into HH:MM:SS so it would look like 00:00:16.

Have done a search but haven't found anything relavent.

Do I need to use a regex?

Help much appreciated.

Thanks in advance.

0

1 Answer 1

117

function secondsToHms(d) {
    d = Number(d);

    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    return ('0' + h).slice(-2) + ":" + ('0' + m).slice(-2) + ":" + ('0' + s).slice(-2);
}

document.writeln('secondsToHms(10) = ' + secondsToHms(10) + '<br>');
document.writeln('secondsToHms(30) = ' + secondsToHms(30) + '<br>');
document.writeln('secondsToHms(60) = ' + secondsToHms(60) + '<br>');
document.writeln('secondsToHms(100) = ' + secondsToHms(100) + '<br>');
document.writeln('secondsToHms(119) = ' + secondsToHms(119) + '<br>');
document.writeln('secondsToHms(500) = ' + secondsToHms(500) + '<br>');

6
  • 3
    I like the simplicity of this answer, but I combined it with this answer modifying the first two lines to Number.prototype.toHHMMSS = function () { d = this; to make it even more concise.
    – alunsford3
    May 25, 2012 at 5:40
  • 1
    Nice - I corrected a small bug where for h > 0 and m = 0 it wasn't padding the minutes to 00. I've submitted it as an edit to your answer, as the question is closed to new answers.
    – Matt
    Mar 31, 2015 at 18:55
  • 6
    You can use moment.js: moment().startOf('day').seconds(16.4534).format('HH:mm:ss') - it's as simple as that.
    – elquimista
    Mar 4, 2016 at 18:16
  • 2
    If the seconds == 0, this returns 0:00 instead of what I would expect to be 00:00:00 Apr 18, 2016 at 6:27
  • 1
    The answer above can be improved by conditional return value like this if (h > 0) { return ( ("0" + h).slice(-2) + ":" + ("0" + m).slice(-2) + ":" + ("0" + s).slice(-2) ); } return ("0" + m).slice(-2) + ":" + ("0" + s).slice(-2); to avoid 00 when the time has not reached hour
    – Jokanola
    Jan 3, 2022 at 8:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.