Convert seconds to HH:MM:SS in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Convert seconds to HH:MM:SS in JavaScript #

To convert seconds to HH:MM:SS:

  1. Multiply the seconds by 1000 to get milliseconds.
  2. Pass the milliseconds to the Date() constructor.
  3. Use the toISOString() method on the Date object.
  4. Get the hh:mm:ss portion of the string.
index.js
const seconds = 600; // ✅ get hh:mm:ss string const result = new Date(seconds * 1000).toISOString().slice(11, 19); console.log(result); // 👉️ "00:10:00" (hh:mm:ss) // ✅ if seconds are less than 1 hour and you only need mm:ss const result2 = new Date(seconds * 1000).toISOString().slice(14, 19); console.log(result2); // 👉️ "10:00" (mm:ss)

We converted the seconds to milliseconds by multiplying them by 1000.

The Date() constructor takes milliseconds as a parameter and returns a Date object that we used to leverage built-in methods.

The toISOString method returns a string representation of the date in the ISO 8601 format - YYYY-MM-DDTHH:mm:ss.sssZ.

index.js
const seconds = 600; // 👇️ "1970-01-01T00:10:00.000Z" console.log(new Date(seconds * 1000).toISOString());
At this point, all we have to do is get the portion of the string between the T character, which is the marker that the time portion of the date starts, and the dot ., which precedes the milliseconds.

We used the slice method to get the substring from the character at index 11 up to (but not including) the character at index 19.

index.js
const seconds = 600; // 👇️ "1970-01-01T00:10:00.000Z" console.log(new Date(seconds * 1000).toISOString()); // ✅ get hh:mm:ss string const result = new Date(seconds * 1000).toISOString().slice(11, 19); console.log(result); // 👉️ "00:10:00" (hh:mm:ss)

You can format the time as mm:ss if the seconds you want to convert are less than 1 hour (3600 seconds).

index.js
const seconds = 600; // 👇️ "1970-01-01T00:10:00.000Z" console.log(new Date(seconds * 1000).toISOString()); // ✅ if seconds are less than 1 hour and you only need mm:ss const result2 = new Date(seconds * 1000).toISOString().slice(14, 19); console.log(result2); // 👉️ "10:00" (mm:ss)

This time we used the slice method to get a substring from character 14 up to (but not including) character 19.

This only returns the mm:ss portion of the string.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.