Home >Web Front-end >JS Tutorial >How to Convert Seconds to HH:MM:SS Time String in JavaScript?

How to Convert Seconds to HH:MM:SS Time String in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-25 09:51:02968browse

How to Convert Seconds to HH:MM:SS Time String in JavaScript?

Convert Seconds to Time String in JavaScript (hh:mm:ss)

Often, we need to convert a duration in seconds to a human-readable time string formatted as hours:minutes:seconds. This can be easily achieved in JavaScript using a simple algorithm involving mathematical calculations and string concatenation.

To convert seconds to the desired time string, we first need to extract the hours, minutes, and seconds from the given number of seconds.

Here's the JavaScript snippet for converting seconds to a colon-separated time string:

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;
}

Usage:

alert("5678".toHHMMSS());

Output:

01:34:38

The above is the detailed content of How to Convert Seconds to HH:MM:SS Time String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn