1function convertHMS(value) {
2 const sec = parseInt(value, 10); // convert value to number if it's string
3 let hours = Math.floor(sec / 3600); // get hours
4 let minutes = Math.floor((sec - (hours * 3600)) / 60); // get minutes
5 let seconds = sec - (hours * 3600) - (minutes * 60); // get seconds
6 // add 0 if value < 10; Example: 2 => 02
7 if (hours < 10) {hours = "0"+hours;}
8 if (minutes < 10) {minutes = "0"+minutes;}
9 if (seconds < 10) {seconds = "0"+seconds;}
10 return hours+':'+minutes+':'+seconds; // Return is HH : MM : SS
11}
12
1function secondsToHms(d) {
2 d = Number(d);
3 var h = Math.floor(d / 3600);
4 var m = Math.floor(d % 3600 / 60);
5 var s = Math.floor(d % 3600 % 60);
6
7 var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
8 var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
9 var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
10 return hDisplay + mDisplay + sDisplay;
11}
1 var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
2 console.log(myDate)
3//using regex
1// just added 2 formats in Glorious Guanaco code
2function secondsToHms(value) {
3 const sec = parseInt(value, 10);
4 let hours = Math.floor(sec / 3600);
5 let minutes = Math.floor((sec - hours * 3600) / 60);
6 let seconds = sec - hours * 3600 - minutes * 60;
7 if (hours < 10) { hours = '0' + hours; }
8 if (minutes < 10) { minutes = '0' + minutes; }
9 if (seconds < 10) { seconds = '0' + seconds; }
10 if (hours == 0) {
11 return +minutes + ':' + seconds; // Return in MM:SS format
12 } else {
13 return hours + ':' + minutes + ':' + seconds; // Return in HH:MM:SS format
14 }
15 }
1String.prototype.toHHMMSS = function () {
2 var sec_num = parseInt(this, 10); // don't forget the second param
3 var hours = Math.floor(sec_num / 3600);
4 var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
5 var seconds = sec_num - (hours * 3600) - (minutes * 60);
6
7 if (hours < 10) {hours = "0"+hours;}
8 if (minutes < 10) {minutes = "0"+minutes;}
9 if (seconds < 10) {seconds = "0"+seconds;}
10 return hours+':'+minutes+':'+seconds;
11}
12
1function str_pad_left(string,pad,length) {
2 return (new Array(length+1).join(pad)+string).slice(-length);
3}
4
5var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);
6