Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert seconds to HH-MM-SS with JavaScript?

How can I convert seconds to an HH-MM-SS string using JavaScript?

like image 507
Hannoun Yassir Avatar asked Aug 24 '09 14:08

Hannoun Yassir


People also ask

How do you convert seconds to HH MM SS?

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.

How do you convert seconds to HH MM SS in Python?

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.

How do you get time in HH MM SS?

To show current time in JavaScript in the format HH:MM:SS, we use the date's toLocaleTimeString method. const d = new Date(); console.


2 Answers

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); 
like image 148
Harish Anchu Avatar answered Oct 09 '22 03:10

Harish Anchu


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.

like image 30
Cleiton Avatar answered Oct 09 '22 05:10

Cleiton