Home > Web Front-end > JS Tutorial > How Can I Convert Seconds to HH:MM:SS Format in JavaScript?

How Can I Convert Seconds to HH:MM:SS Format in JavaScript?

Susan Sarandon
Release: 2024-11-24 19:26:15
Original
949 people have browsed it

How Can I Convert Seconds to HH:MM:SS Format in JavaScript?

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);
Copy after login

Explanation:

  1. Creating a Date object: We create a Date object with a null value, which represents a timestamp of 0.
  2. Setting seconds: We set the seconds of the Date object to the specified number of seconds.
  3. Extracting the HH-MM-SS string: We convert the Date object to an ISO string and then slice off the HH-MM-SS portion (from index 11 to 19).

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"
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template