. Advertisement .
. Advertisement .
So, the question arises of how to get the time in HH:MM:SS. Check out what you need to do
Converting seconds to HH:MM:SS is really a simple process. Four procedures are used to convert it into the standard hour, minute, and second format. Check out what you need to do
- To get milliseconds, multiply the seconds by ‘1000’.
Date()Constructor for passing milliseconds.
toISOString()method on the ‘Date’.
- Get the hh:mm:ss
const sample_seconds = 1000; // Get hh:mm:ss string const result1 = new Date(sample_seconds * 1000).toISOString().slice(11, 19); console.log(result1);
If seconds are less than 1 hour and you only need mm:ss, you need to run the following code:
const sample_seconds2 = 1100; const result2 = new Date(sample_seconds2 * 1000).toISOString().slice(14, 19); console.log(result2);
Here, multiplying seconds by ‘1000’ returns milliseconds, then the milliseconds took by the
Date() constructor and return the Date object that we use control inbuilt methods.
The toISOString() Method
To get the date in ISO format ‘YYYY-MM-DDTHH:mm:ss:sssZ, the
toISOString() method is used. Have look at the code:
const sample_seconds3 = 1250; console.log(new Date(sample_seconds3 * 1000).toISOString());
Here, in this code, you can see that there is a ‘T’ character. The purpose of the ‘T’ character is the marking point that separates it from the time. Whereas, you can also see a ‘dot’, which is placed to separate the milliseconds.
The slice() Method
It Is used to obtain the substring from the character at the ‘11’ index up to the ‘19’ index. This example is to explain the method that we used in the first code where we used index ’11’ and ‘19’.
Have a look at the example:
const sample_seconds4 = 1300; console.log(new Date(sample_seconds4 * 1000).toISOString()); const result3 = new Date(sample_seconds4 * 1000).toISOString().slice(11, 19); console.log(result3);
Use ‘mm:ss’ Format
There is a scenario. When you are converting seconds, and then you find out that the seconds that you are trying to convert are less than ‘1’ hour. We need to still get it converted, and this is how you can do it:
const sample_seconds5 = 1400; console.log(new Date(sample_seconds5 * 1000).toISOString()); const result4 = new Date(sample_seconds5 * 1000).toISOString().slice(14, 19); console.log(result4);
slice() method is used to get the substring from the ‘14’ character to the ‘19’ character. We get ‘mm:ss’ format in return.