Effortlessly Transform Seconds into hh:mm:ss Format Using JavaScript
Written on
Chapter 1: Introduction to Time Conversion
In JavaScript applications, there are times when we need to transform a given number of seconds into a formatted time string, specifically in the hh:mm:ss style. This article will explore the process of achieving this conversion effectively.
Section 1.1: Crafting a Custom Conversion Function
To convert seconds into the hh:mm:ss format, we can design our own function. Below is an example of how such a function might look:
const toHHMMSS = (numSecs) => {
let secNum = parseInt(numSecs, 10);
let hours = Math.floor(secNum / 3600).toString().padStart(2, '0');
let minutes = Math.floor((secNum - (hours * 3600)) / 60).toString().padStart(2, '0');
let seconds = (secNum - (hours * 3600) - (minutes * 60)).toString().padStart(2, '0');
return ${hours}:${minutes}:${seconds};
}
console.log(toHHMMSS(1234));
In this toHHMMSS function, we first convert numSecs into an integer. Next, we calculate the hours by dividing secNum by 3600, rounding down to the nearest whole number using Math.floor. We then convert this result to a string and ensure it's two digits long with padStart.
After computing the hours, we derive the minutes by subtracting the hours in seconds from secNum, then dividing the remainder by 60. This too is rounded down and formatted similarly. Finally, we calculate the seconds by subtracting both the hour and minute contributions from secNum, formatting this final result into a two-digit string.
Thus, calling console.log(toHHMMSS(1234)) will output: '00:20:34'.
Section 1.2: Utilizing Date Methods for Conversion
Another approach to convert seconds into the hh:mm:ss format is by leveraging the Date object's toISOString method. Here's how to implement this method:
const date = new Date(0);
date.setSeconds(1234);
const timeString = date.toISOString().substr(11, 8);
console.log(timeString);
In this example, we create a new Date object initialized to a timestamp of 0. By calling setSeconds, we set the date's seconds to the desired number. Then, using toISOString, we obtain a standardized date string and extract the substring that contains the hours, minutes, and seconds.
Consequently, timeString will also yield: '00:20:34'.
In this video, we demonstrate how to convert seconds into the hh:mm:ss format using JavaScript functions.
Chapter 2: Conclusion
In summary, converting elapsed seconds into the hh:mm:ss format can be efficiently achieved in JavaScript using custom functions or built-in date methods. Both methods provide a straightforward means to represent time in an easily understandable format.
This video further elaborates on how to convert seconds to HH-MM-SS format using JavaScript, showcasing various techniques.