Converting Seconds to HH-MM-SS Format in JavaScript
A common task when working with timestamps is converting seconds to a human-readable format. In JavaScript, this can be achieved without external libraries using the Date method.
Solution:
The following JavaScript code snippet demonstrates how to convert seconds to an HH-MM-SS string:
const date = new Date(null); date.setSeconds(SECONDS); // Replace SECONDS with the number of seconds const result = date.toISOString().slice(11, 19);
Explanation:
Example:
To convert 600 seconds to HH-MM-SS, we would use the following code:
const date = new Date(null); date.setSeconds(600); const result = date.toISOString().slice(11, 19); console.log(result); // Output: "00:10:00"
Alternative One-Line Solution:
As suggested by Frank in the comments, a one-line alternative can be written as:
new Date(SECONDS * 1000).toISOString().slice(11, 19);
The above is the detailed content of How Can I Convert Seconds to HH:MM:SS Format in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!