Convert seconds to HH:MM:SS in JavaScript

avatar

Borislav Hadzhiev

Thu Jan 20 20222 min read

banner

Photo by Joshua Newton

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 allows us to leverage built-in functions.

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 substring after 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 no 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)

If the seconds you want to convert are less than 1 hour (3600 seconds), you can only get the minutes and seconds portion - a string formatted as mm:ss.

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.