Table of Contents
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.
1 2 3 4 5 6 7 8 |
const seconds = 22600 var date = new Date(null); date.setSeconds(seconds); var hhmmssFormat = date.toISOString().substr(11, 8); console.log(hhmmssFormat); |
Output:
1 2 3 |
06:16:40 |
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
1 2 3 4 5 6 7 8 |
const seconds = 22600 var date = new Date(null); date.setSeconds(seconds); var isoFormatDate = date.toISOString(); console.log(isoFormatDate); |
Output:
1 2 3 |
1970-01-01T06:16:40.000Z |
We used substr()
method to get HH:mm:ss
part of String.
substr() methods takes 2 parameters
Start index
: Start index of substringLength 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 inHH:MM:SS
format.
1 2 3 4 5 6 |
seconds = 22600 var hhmmssFormat = new Date(seconds * 1000).toISOString().substr(11, 8); console.log(hhmmssFormat); |
Output:
1 2 3 |
06:16:40 |
If number of seconds are less than 3600, you can remove hours part and format the string in minutes and seconds.
1 2 3 4 5 6 |
seconds = 260 var mmssFormat = new Date(seconds * 1000).toISOString().substr(14, 5); console.log(mmssFormat); |
Output:
1 2 3 |
04:20 |
Using momentJs library
You can also use moment js library to get seconds to hours minutes seconds format.
1 2 3 4 5 6 |
var result= moment().startOf('day') .seconds(22600) .format('HH:MM:ss'); console.log(result); |
Output:
1 2 3 |
06:16:40 |
That’s all about how to convert seconds to hours minutes seconds in JavaScript.