Convert seconds to HH-MM-SS format in JavaScript

By Faruque Ahamed Mollick

In this tutorial, I am going to show you how to convert seconds to Hours Minutes Seconds (HH-MM-SS) format in JavaScript.

Play/Pause Button For HTML5 Video Using JavaScript

You may need to convert seconds into a well-formatted structure so that it become easy to understand. Suppose you are measuring the duration of an event in JavaScript and the seconds is consist of a large number.

Then it will be really hard to get the idea of time. So it is better to convert it into a well formatted time. So I am going to tell you how to convert seconds into the HH-MM-SS format.

Here is the JavaScript code that you can see below:

var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);

So you can see that it is a very simple and easy way to convert seconds into HH-MM-SS formatted time. Here in this example code, I have specified the seconds as 4995 and it returns the 1 as the hour, 23 as minutes and 15 as seconds. It returns the output 01:23:15.



Simple Animation Example Using jQuery

You can also try the above code and test it. You will get the well formatted time from seconds.

Alternative way of converting seconds in HH-MM-SS format

You can also convert seconds using mathematical operations. Here you are going to see an alternate method.

Below is another example code of doing the same task with the mathematical operation:

hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;

Source of the code: https://stackoverflow.com/questions/1322732/convert-seconds-to-hh-mm-ss-with-javascript

 

So, you have seen two different methods to convert seconds into Hours Minutes And Seconds (hh-mm-ss). Which method do you prefer most?

Below is the comment box. You can tell about your preferred method.

Leave a Reply

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