Convert Seconds to Hours Minutes Seconds in Javascript

In this post, we will see how to convert seconds to Hours Minutes Seconds in JavaScript.

There are multiple ways to do it. Let’s go through them.

Using javascript without any external library

To convert seconds to Hours Minutes Seconds in javascript:

  • Create new date object with its constructor.
  • Pass seconds to setSeconds() method on date object.
  • Use toISOString() to convert date to ISOString format.
  • Use substr() to get string in HH:mm:ss format.

Output:

We created new Date object and called setSeconds() method on date object.

toISOString() method returns ISO 8601 string representation of Date – YYYY-MM-DDTHH:mm:ss.sssZ

Output:

We used substr() method to get HH:mm:ss part of String.

substr() methods takes 2 parameters

  • Start index: Start index of substring
  • Length of String: Length of substring.

As we were looking for string after T part of ISO format string, we have used substr with start index 11 and length of String as 8.

You can also use alternative method:

  • Multiply seconds with 1000.
  • Pass it to Date‘s constructor
  • Use toISOString() to convert it to ISOString format’
  • Use substr() to get string in HH:MM:SS format.

Output:

If number of seconds are less than 3600, you can remove hours part and format the string in minutes and seconds.

Output:

Using momentJs library

You can also use moment js library to get seconds to hours minutes seconds format.

Output:

That’s all about how to convert seconds to hours minutes seconds in JavaScript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *