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.

Community
  • 1
  • 1
shahidaltaf
  • 585
  • 1
  • 5
  • 17

1 Answers1

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>');
blex
  • 24,941
  • 5
  • 39
  • 72
Thorben
  • 6,871
  • 2
  • 19
  • 19
  • 3
    I like the simplicity of this answer, but I combined it with [this answer](http://stackoverflow.com/a/6313008/396381) modifying the first two lines to `Number.prototype.toHHMMSS = function () { d = this;` to make it even more concise. – alunsford3 May 25 '12 at 05: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 '15 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 04 '16 at 18:16
  • 2
    If the seconds == 0, this returns 0:00 instead of what I would expect to be 00:00:00 – Douglas Gaskell Apr 18 '16 at 06: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 03 '22 at 08:05
  • Another option to omit unneeded sections is to add the values to an array, then return the array joined with a colon separator. `const parts = [('0' + s).slice(-2)];` `if (m || (!m && h)) parts.unshift(('0' + m).slice(-2));` `if (h) parts.unshift(('0' + h).slice(-2));` `return parts.join(":");` – Justin S Barrett Aug 26 '22 at 16:01