Introduction
In this lab, we will explore the formatSeconds function in JavaScript. This function returns the ISO format of a given number of seconds by dividing the seconds into appropriate values for hours, minutes and seconds. We will learn how to use Array.prototype.map(), Math.floor(), String.prototype.padStart() and Array.prototype.join() to format and combine the values into a string. By the end of this lab, you will have a solid understanding of how to manipulate and format time data in JavaScript.
Function to Format Seconds as ISO Time
To use this code, open the Terminal/SSH and type node. This function takes a number of seconds as an argument and returns the ISO time format. Here's how it works:
- Divide the number of seconds by the appropriate values to obtain the corresponding values for
hour,minuteandsecond. - Store the sign of the number in a variable to prepend it to the result.
- Use
Array.prototype.map()in combination withMath.floor()andString.prototype.padStart()to stringify and format each segment. - Use
Array.prototype.join()to combine the values into a string.
Here's the code:
const formatSeconds = (s) => {
const [hour, minute, second, sign] =
s > 0
? [s / 3600, (s / 60) % 60, s % 60, ""]
: [-s / 3600, (-s / 60) % 60, -s % 60, "-"];
return (
sign +
[hour, minute, second]
.map((v) => `${Math.floor(v)}`.padStart(2, "0"))
.join(":")
);
};
You can test the function with these examples:
formatSeconds(200); // '00:03:20'
formatSeconds(-200); // '-00:03:20'
formatSeconds(99999); // '27:46:39'
Summary
Congratulations! You have completed the Number of Seconds to ISO Format lab. You can practice more labs in LabEx to improve your skills.