Home >Web Front-end >JS Tutorial >How to Convert Seconds to hh:mm:ss Time Format in JavaScript?
Converting Seconds to Colon-Separated Time Strings with hh:mm:ss Format
Converting a duration from seconds to a human-readable time string in the hh:mm:ss format can be a common task in web development. This is especially useful for displaying the duration of media playback, timers, or any other scenario where precise time representation is required.
Let's explore a straightforward and efficient JavaScript snippet that accomplishes this conversion seamlessly:
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; }
Here's how you can utilize this function to convert seconds to the desired time string:
alert("5678".toHHMMSS());
This will output the string "1:34:38" in the hh:mm:ss format. The function takes care of zero-padding the hours, minutes, and seconds if they are less than 10 to maintain the desired formatting.
To illustrate this further, let's consider a scenario where you have a media player displaying the elapsed duration of a video. Using this snippet, you can dynamically update the time display every second to provide an accurate time indication to the user.
The above is the detailed content of How to Convert Seconds to hh:mm:ss Time Format in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!