I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)
I found some useful answers here but they all talk about converting to x hours and x minutes format.
So is there a tiny snippet that does this in jQuery or just raw JavaScript?
const hms = '02:04:33'; const [hours, minutes, seconds] = hms. split(':'); const totalSeconds = (+hours) * 60 * 60 + (+minutes) * 60 + (+seconds); console. log(totalSeconds);
To convert seconds to HH:MM:SS :Multiply the seconds by 1000 to get milliseconds. Pass the milliseconds to the Date() constructor. Use the toISOString() method on the Date object.
To show current time in JavaScript in the format HH:MM:SS, we use the date's toLocaleTimeString method. const d = new Date(); console.
HH:mm:ss - this format displays a 24-hour digital clock with leading zero for hours. It also displays minutes and seconds.
String.prototype.toHHMMSS = function () { var sec_num = parseInt(this, 10); // don't forget the second param var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); if (hours < 10) {hours = "0"+hours;} if (minutes < 10) {minutes = "0"+minutes;} if (seconds < 10) {seconds = "0"+seconds;} return hours+':'+minutes+':'+seconds; }
You can use it now like:
alert("5678".toHHMMSS());
Working snippet:
String.prototype.toHHMMSS = function () { var sec_num = parseInt(this, 10); // don't forget the second param var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); if (hours < 10) {hours = "0"+hours;} if (minutes < 10) {minutes = "0"+minutes;} if (seconds < 10) {seconds = "0"+seconds;} return hours + ':' + minutes + ':' + seconds; } console.log("5678".toHHMMSS());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With