Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  11] [ 5]  / answers: 1 / hits: 169123  / 9 Years ago, fri, july 10, 2015, 12:00:00

How can I convert seconds to HH:mm:ss?



At the moment I am using the function below



render: function (data){
return new Date(data*1000).toTimeString().replace(/.*(d{2}:d{2}:d{2}).*/, $1);;
}


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



render: function (data){
return moment(data).format('HH:mm:ss');
}


What am I doing wrong?



EDIT



I managed to find a solution without moment.js which is as follow



return (new Date(data * 1000)).toUTCString().match(/(dd:dd:dd)/)[0];


Still curious on how I can do it in moment.js


More From » momentjs

 Answers
6

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]);
}
*/




[#65858] Wednesday, July 8, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
collinisaaka

Total Points: 194
Total Questions: 105
Total Answers: 104

Location: Tonga
Member since Tue, Nov 30, 2021
3 Years ago
;