How to convert seconds to HH:mm:ss in moment.js

This is similar to the answer mplungjan referenced from another post, but more concise:

const secs = 456;

const formatted = moment.utc(secs*1000).format('HH:mm:ss');

document.write(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.


From this post I would try this to avoid leap issues

moment("2015-01-01").startOf('day')
    .seconds(s)
    .format('H:mm:ss');

I did not run jsPerf, but I would think this is faster than creating new date objects a million times

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

for (var i=60;i<=60*60*5;i++) {
 document.write(hhmmss(i)+'<br/>');
}


/* 
function show(s) {
  var d = new Date();
  var d1 = new Date(d.getTime()+s*1000);
  var  hms = hhmmss(s);
  return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);
}    
*/


You can use moment-duration-format plugin:

var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
<!-- Moment.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

See also this Fiddle

Upd: To avoid trimming for values less than 60-sec use { trim: false }:

var formatted = duration.format("hh:mm:ss", { trim: false }); // "00:00:05"