Time Duration
Part of the Logic & Flow section of Coddy's GO journey — lesson 62 of 68.
When working with time in Go, you'll often need to represent periods of time - like "5 minutes" or "2 hours". Go provides the time.Duration type specifically for this purpose.
A time.Duration represents a span of time between two instants. Go includes several predefined constants that make creating durations simple and readable:
tenMinutes := 10 * time.Minute
twoHours := 2 * time.Hour
thirtySeconds := 30 * time.SecondThe most commonly used duration constants are time.Nanosecond, time.Microsecond, time.Millisecond, time.Second, time.Minute, and time.Hour. You can multiply these constants by integers to create the exact duration you need.
Duration values are essential for time arithmetic, scheduling operations, and controlling timing in your programs. They work seamlessly with other time functions and provide a clear, readable way to express time spans in your code.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a workout session timer that uses time.Duration to track different exercise intervals and rest periods. This challenge will test your ability to create duration values using Go's predefined constants and perform calculations with them.
You will receive two inputs:
- A string containing exercise definitions in the format
"exercise1:duration_value:duration_unit,exercise2:duration_value:duration_unit"(e.g.,"Push-ups:30:Second,Plank:2:Minute,Squats:45:Second") - A string containing rest period information in the format
"rest_duration_value:rest_duration_unit"(e.g.,"15:Second")
Your task is to:
- Parse the first input by splitting on commas to get individual exercise entries
- For each exercise entry, split on colons to extract the exercise name, duration value (as string), and duration unit
- Parse the second input by splitting on colons to get rest duration value and unit
- Convert duration values from strings to integers and create
time.Durationobjects using the appropriate constants:- For
"Second": multiply bytime.Second - For
"Minute": multiply bytime.Minute - For
"Hour": multiply bytime.Hour
- For
- Display the application header:
"=== WORKOUT SESSION TIMER ===" - Display the session setup:
"Setting up workout session..." - For each exercise, display:
"Exercise: [exercise_name] - Duration: [duration_object]" - Display the rest period:
"Rest period between exercises: [rest_duration_object]" - Calculate and display session breakdown:
"=== SESSION BREAKDOWN ==="- For each exercise:
"[exercise_name]: [duration_in_seconds] seconds" "Rest periods: [rest_duration_in_seconds] seconds each"
- Calculate total session time (sum of all exercise durations plus rest periods between exercises):
"=== TIMING CALCULATIONS ===""Total exercise time: [total_exercise_duration_object]""Total rest time: [total_rest_duration_object]"(rest periods between exercises, so one less than number of exercises)"Complete session duration: [total_session_duration_object]"
- Display session statistics:
"=== SESSION STATISTICS ===""Number of exercises: [number_of_exercises]""Longest exercise: [longest_exercise_name] ([longest_duration_object])""Shortest exercise: [shortest_exercise_name] ([shortest_duration_object])""Average exercise duration: [average_duration_in_seconds] seconds"
- Display time conversions:
"=== TIME CONVERSIONS ===""Session duration in minutes: [total_minutes]"(convert total session duration to minutes)"Session duration in hours: [total_hours]"(convert total session duration to hours, show as decimal)
- Display the completion message:
"Workout session timer configured successfully"
Use the time package to work with durations, the strings package to split input strings, the strconv package to convert string numbers to integers, and the fmt package for formatted output. Remember that time.Duration values can be added together and converted to different units using methods like Seconds(), Minutes(), and Hours(). This challenge demonstrates how to create and manipulate duration values for timing applications.
Cheat sheet
Go provides the time.Duration type to represent periods of time between two instants.
Create durations using predefined constants multiplied by integers:
tenMinutes := 10 * time.Minute
twoHours := 2 * time.Hour
thirtySeconds := 30 * time.SecondCommon duration constants include:
time.Nanosecondtime.Microsecondtime.Millisecondtime.Secondtime.Minutetime.Hour
Duration values can be added together and converted to different units using methods like Seconds(), Minutes(), and Hours().
Try it yourself
package main
import (
"fmt"
"strconv"
"strings"
"time"
)
func main() {
// Read input
var exerciseInput string
var restInput string
fmt.Scanln(&exerciseInput)
fmt.Scanln(&restInput)
// Parse exercises from input
exerciseEntries := strings.Split(exerciseInput, ",")
// Parse rest period from input
restParts := strings.Split(restInput, ":")
// TODO: Write your code below
// 1. Parse each exercise entry to extract name, duration value, and unit
// 2. Convert duration values to integers and create time.Duration objects
// 3. Parse rest duration and create time.Duration object
// 4. Display workout session information and calculations
// 5. Calculate session statistics and time conversions
// Remember to output all the required information as specified in the challenge
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors