Welcome! In today's lesson, we'll explore the practical applications of string operations and type conversions in Go. These concepts are crucial in many programming tasks. We'll dive into a real-world example: time parsing. Have you ever wondered how to add a specific number of seconds to a given time? By the end of today's session, you'll be able to calculate this using Go. 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 given an integer representing a certain number of seconds. Your task is to calculate the new time after adding the provided seconds and output the result in 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 solving this task:
- The input time is always a valid time string in the
HH:MM:SS
format, withHH
ranging from 00 to 23, andMM
andSS
ranging from 00 to 59. - The output should maintain the same format.
- While Go provides a robust
time
package for handling time and date calculations, our focus in this course is on string operations, so we will not be using it and instead rely on plain strings to represent time.
Let's go ahead and break down how to achieve this with a step-by-step solution guide.
Our first step involves parsing the input time string. We aim to extract the hours, minutes, and seconds as integer values for further calculations. In Go, we can use strings.Split
to divide the string at ":" and convert each substring into an integer:
Go1import ( 2 "fmt" 3 "strconv" 4 "strings" 5) 6 7func main() { 8 time := "12:34:56" 9 timeParts := strings.Split(time, ":") 10 hours, _ := strconv.Atoi(timeParts[0]) 11 minutes, _ := strconv.Atoi(timeParts[1]) 12 seconds, _ := strconv.Atoi(timeParts[2]) 13 14 fmt.Println(hours, minutes, seconds) 15}
This operation successfully parses the time string and converts 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:
Go1secondsSinceStart := hours*3600 + minutes*60 + seconds
This expression computes the cumulative number of seconds from the start of the day.
Now we need to add the integer representing a number of seconds to our computed secondsSinceStart
, and also consider cases where the added seconds roll over into the next day:
Go1additionalSeconds := 123 2totalSeconds := (secondsSinceStart + additionalSeconds) % (24 * 3600)
The modulus operator %
ensures that our totalSeconds
value doesn't exceed the total number of seconds in a day (86,400
or 24 * 3600
seconds).
In this step, we reverse the previous operation. We are given an integer number of seconds and need to convert this back into a time string in the HH:MM:SS
format. We use the division /
and modulo %
operations directly to convert these values:
Go1hours = totalSeconds / 3600 2totalSeconds %= 3600 3minutes = totalSeconds / 60 4seconds = totalSeconds % 60
The final step is to assemble these values into our HH:MM:SS
format string using fmt.Sprintf
:
Go1result := fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
In Go, fmt.Sprintf
allows us to format strings with zero-padded numbers easily, ensuring that all time units are consistently formatted with two digits, whether they are single or double-digit numbers. The format verbs like %02d
indicate that the corresponding integer should be represented as a two-digit number, with a leading zero if necessary.
Let's collate all the individual steps and formulate the final function:
Go1package main 2 3import ( 4 "fmt" 5 "strconv" 6 "strings" 7) 8 9func timeAdder(time string, secondsToAdd int) string { 10 timeParts := strings.Split(time, ":") 11 hours, _ := strconv.Atoi(timeParts[0]) 12 minutes, _ := strconv.Atoi(timeParts[1]) 13 seconds, _ := strconv.Atoi(timeParts[2]) 14 15 secondsSinceStart := hours*3600 + minutes*60 + seconds 16 totalSeconds := (secondsSinceStart + secondsToAdd) % (24 * 3600) 17 18 hours = totalSeconds / 3600 19 totalSeconds %= 3600 20 minutes = totalSeconds / 60 21 seconds = totalSeconds % 60 22 23 return fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds) 24} 25 26func main() { 27 // Call the function 28 fmt.Println(timeAdder("05:10:30", 123)) 29}
And there you have it! You've crafted a solution that calculates the new time based on the provided time and the number of seconds elapsed since then.
Congratulations! You've learned how to parse a time string and utilize type conversions to compute the number of seconds elapsed from the beginning of the day in Go. Following this, you learned how to perform the reverse operation: to calculate the time based on the number of seconds since the start of the day. In this lesson, we practiced essential Go skills, including string operations and fundamental integer operations. Continue practicing with similar problems to reinforce your skills, and these tasks will soon become second nature. See you in our next session, and happy coding!