Let me show you how to convert a second value to HH:mm:ss or hour, minute, seconds format. We can use the toISOString() and the Date constructor to do the conversion.
Other methods of the Date class can be called on this instance.
The toISOString method is an inbuilt method of the Date class. It returns a string representation of the date in ISO 8601. It looks as below:
As you can see here, it includes the required HH:mm:ss values.
As explained above, we can follow these steps to convert a seconds value to HH:mm:ss:
- Get the time in seconds from the user.
- Multiply it by 1000 to convert it to milliseconds.
- Pass the milliseconds to the Date constructor to create an instance of Date.
- Call the toISOString() method on this instance to get the ISO 8601 format date-time string.
- As the output of toISOString() is in
YYYY-MM-DDTHH:mm:ss.sssZformat, we have to pick the substring from index 11 to 19. We can use the slice() method.
If I combine these steps, the complete program will be:
let seconds = 2200; let date = new Date(seconds * 1000); let isoDate = date.toISOString(); let timeStr = isoDate.slice(11, 19); console.log("HH:mm:ss : ", timeStr);
- The seconds is assigned to the variable seconds.
- One instance of Date is created by passing the milliseconds value to the Date constructor.
- The ISO string is assigned to the variable isoDate.
- By using the slice method, the HH:mm:ss time string is created and assigned it to the timeStr variable.
- The last line is printing the result time string.
If you run this program, it will print the below output:
HH:mm:ss : 00:36:40
let seconds = 4222; let date = new Date(seconds * 1000); let isoDate = date.toISOString(); let timeStr = isoDate.slice(11, 19).replaceAll(':', '-'); console.log("HH-mm-ss : ", timeStr);
It will print:
HH-mm-ss : 01-10-22