How can I convert seconds to HH:mm:ss
?
At the moment I am using the function below
JavaScript
x
4
1
render: function (data){
2
return new Date(data*1000).toTimeString().replace(/.*(d{2}:d{2}:d{2}).*/, "$1");;
3
}
4
This works on chrome but in firefox for 12 seconds I get 01:00:12
I would like to use moment.js for cross browser compatibility
I tried this but does not work
JavaScript
1
4
1
render: function (data){
2
return moment(data).format('HH:mm:ss');
3
}
4
What am I doing wrong?
EDIT
I managed to find a solution without moment.js which is as follow
JavaScript
1
2
1
return (new Date(data * 1000)).toUTCString().match(/(dd:dd:dd)/)[0];
2
Still curious on how I can do it in moment.js
Advertisement
Answer
From this post I would try this to avoid leap issues
JavaScript
1
4
1
moment("2015-01-01").startOf('day')
2
.seconds(s)
3
.format('H:mm:ss');
4
I did not run jsPerf, but I would think this is faster than creating new date objects a million times
JavaScript
1
12
12
1
function pad(num) {
2
return ("0"+num).slice(-2);
3
}
4
function hhmmss(secs) {
5
var minutes = Math.floor(secs / 60);
6
secs = secs%60;
7
var hours = Math.floor(minutes/60)
8
minutes = minutes%60;
9
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
10
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
11
}
12
JavaScript
1
25
25
1
function pad(num) {
2
return ("0"+num).slice(-2);
3
}
4
function hhmmss(secs) {
5
var minutes = Math.floor(secs / 60);
6
secs = secs%60;
7
var hours = Math.floor(minutes/60)
8
minutes = minutes%60;
9
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
10
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
11
}
12
13
for (var i=60;i<=60*60*5;i++) {
14
document.write(hhmmss(i)+'<br/>');
15
}
16
17
18
/*
19
function show(s) {
20
var d = new Date();
21
var d1 = new Date(d.getTime()+s*1000);
22
var hms = hhmmss(s);
23
return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"n"+d.toString().split("GMT")[0]+"n"+d1.toString().split("GMT")[0]);
24
}
25
*/