Welcome! In this lesson, we will explore the practical applications of string operations and type conversions in JavaScript. These concepts are crucial and are used in many programming areas. We'll examine a real-world example: time parsing. Have you ever wondered how to add a certain number of seconds to a specific time? By the end of today's session, you'll be equipped to calculate this using JavaScript. Let's get started!
Imagine this: You receive a time formatted as a string in HH:MM:SS
, where HH
, MM
, and SS
denote the hour, minute, and second, respectively. You are also given an integer representing a certain number of seconds. Your task is to calculate the new time after adding the provided seconds, then output the result in the HH:MM:SS
format.
For example, if the input time is 05:10:30
and the number of seconds to add is 123
, the output should be 05:12:33
since 123
seconds translate to 2
minutes and 3
seconds.
Please note these points when resolving this task:
HH:MM:SS
format, with HH
ranging from 00 to 23 and MM
and SS
ranging from 00 to 59.Now let's go ahead and break down how to achieve this in our step-by-step solution guide.
Our first step involves parsing the input time string. We aim to extract the hours, minutes, and seconds from this string as integer values for further calculations. In JavaScript, we can use the split
method to divide the string at ":"
and convert each substring into an integer:
JavaScript1let time = "12:34:56"; 2let secondsToAdd = 10; 3let timeParts = time.split(":"); 4let hours = parseInt(timeParts[0]); 5let minutes = parseInt(timeParts[1]); 6let seconds = parseInt(timeParts[2]);
By executing this operation, we've successfully parsed the time string and converted the hours, minutes, and seconds into integers.
Now that we have the hours, minutes, and seconds in integer format, we can efficiently calculate the total number of seconds that have elapsed since the start of the day:
JavaScript1let secondsSinceStart = hours * 3600 + minutes * 60 + seconds;
At this point, your function should compute the cumulative number of seconds from the start of the day.
Now we need to add the integer representing the number of seconds to our computed secondsSinceStart
and also consider cases where the added seconds roll over into the next day:
JavaScript1let totalSeconds = (secondsSinceStart + secondsToAdd) % (24 * 3600);
The modulus operator %
ensures that our totalSeconds
value doesn't exceed the total number of seconds in a day (86400 seconds or 24 * 3600 seconds).
In this step, we reverse the previous operation. We're given an integer number of seconds, and we have to convert this into a time string in the HH:MM:SS
format.
We will use the division /
and modulo %
operations directly to convert these values:
let newHours = Math.floor(totalSeconds / 3600);
. Here, 3600
is the number of seconds in an hour.totalSeconds
to the remainder after extracting the hours: totalSeconds %= 3600;
. This step ensures that totalSeconds
now holds the seconds remaining after accounting for hours.Now, we repeat this process for minutes:
totalSeconds
: let newMinutes = Math.floor(totalSeconds / 60);
. Here, 60
is the number of seconds in a minute.totalSeconds
to the remainder after extracting minutes: totalSeconds %= 60;
. This step ensures that totalSeconds
contains only the seconds remaining after accounting for both hours and minutes.Finally:
totalSeconds
directly gives us the seconds: let newSeconds = totalSeconds;
.So the complete code for this step is:
JavaScript1let newHours = Math.floor(totalSeconds / 3600); 2totalSeconds %= 3600; 3let newMinutes = Math.floor(totalSeconds / 60); 4let newSeconds = totalSeconds % 60;
The final step is to assemble these values into our HH:MM:SS
format string. JavaScript allows us to use template literals for formatting:
JavaScript1let result = `${String(newHours).padStart(2, '0')}:${String(newMinutes).padStart(2, '0')}:${String(newSeconds).padStart(2, '0')}`;
Here, padStart(2, '0')
ensures that each time unit (hours, minutes, and seconds) will be at least 2 characters wide, padding with 0
if necessary.
Let's collate all the individual steps and formulate the final function:
JavaScript1function addSeconds(time, secondsToAdd) { 2 let timeParts = time.split(":"); 3 let hours = parseInt(timeParts[0]); 4 let minutes = parseInt(timeParts[1]); 5 let seconds = parseInt(timeParts[2]); 6 7 let secondsSinceStart = hours * 3600 + minutes * 60 + seconds; 8 let totalSeconds = (secondsSinceStart + secondsToAdd) % (24 * 3600); 9 10 let newHours = Math.floor(totalSeconds / 3600); 11 totalSeconds %= 3600; 12 let newMinutes = Math.floor(totalSeconds / 60); 13 let newSeconds = totalSeconds % 60; 14 15 return `${String(newHours).padStart(2, '0')}:${String(newMinutes).padStart(2, '0')}:${String(newSeconds).padStart(2, '0')}`; 16} 17 18// Call the function 19console.log(addSeconds("05:10:30", 123)); 20// Output: 05:12:33
And voila! You've crafted a function that accurately calculates the new time based on the provided time and the number of seconds that have elapsed since then.
Congratulations! You skillfully learned how to parse a time string and utilize type conversions to calculate the number of seconds elapsed from the beginning of the day. Following this, you learned how to perform the reverse operation: to calculate the time based on the number of seconds that have passed since the beginning of the day. In this lesson, we practiced essential JavaScript skills, including string operations and fundamental integer operations. Continue practicing with similar problems to reinforce your learning, and these tasks will soon become second nature. See you in our next session, and happy coding!