Home > Article > Web Front-end > How to Convert Seconds to HH:MM:SS Format in JavaScript?
Converting Seconds to HH:MM:SS in JavaScript
When working with time-related data, it's often necessary to convert seconds into a human-readable format such as HH:MM:SS. JavaScript provides a simple way to perform this conversion using the Date object.
Solution:
To convert seconds to an HH:MM:SS string in JavaScript, follow these steps:
1. Create a new Date object with the seconds value set to null. 2. Use the setSeconds() method to specify the desired number of seconds. 3. Call the toISOString() method on the Date object to get a string representation in ISO format. 4. Extract the time portion of the string (HH:MM:SS) by slicing from index 11 to index 19.
Example:
const SECONDS = 3600; // 1 hour, specified in seconds const date = new Date(null); date.setSeconds(SECONDS); const result = date.toISOString().slice(11, 19); console.log(result); // Output: 01:00:00
Alternative One-Liner:
As suggested by @Frank, a concise one-liner that achieves the same result is:
new Date(SECONDS * 1000).toISOString().slice(11, 19);
This variant multiplies the seconds by 1000 to convert to milliseconds, which is more convenient for creating a Date object.
The above is the detailed content of How to Convert Seconds to HH:MM:SS Format in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!