How can I convert seconds to an HH-MM-SS
string using JavaScript?
Find the number of whole hours by dividing the number of seconds by 3,600. The number to the left of the decimal point is the number of whole hours. The number to the right of the decimal point is the number of partial hours.
Use the timedelta() constructor and pass the seconds value to it using the seconds argument. The timedelta constructor creates the timedelta object, representing time in days, hours, minutes, and seconds ( days, hh:mm:ss.ms ) format.
To show current time in JavaScript in the format HH:MM:SS, we use the date's toLocaleTimeString method. const d = new Date(); console.
You can manage to do this without any external JavaScript library with the help of JavaScript Date method like following:
var date = new Date(null); date.setSeconds(SECONDS); // specify value for SECONDS here var result = date.toISOString().substr(11, 8);
Or, as per @Frank's comment; a one liner:
new Date(SECONDS * 1000).toISOString().substr(11, 8);
Updated (2020):
Please use @Frank's one line solution:
new Date(SECONDS * 1000).toISOString().substr(11, 8)
If SECONDS<3600 and if you want to show only MM:SS then use below code:
new Date(SECONDS * 1000).toISOString().substr(14, 5)
It is by far the best solution.
Old answer:
Use the Moment.js
library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With