Time Arithmetic
Part of the Logic & Flow section of Coddy's GO journey — lesson 63 of 68.
Now that you understand time.Time objects and time.Duration values, you can perform arithmetic operations to calculate past or future times. Go provides two essential methods for time arithmetic: Add and Sub.
The Add method takes a time.Duration and returns a new time.Time that represents the original time plus the duration:
now := time.Now()
tomorrow := now.Add(24 * time.Hour)
fmt.Println(tomorrow)The Sub method works in two ways. When you subtract one time.Time from another, it returns a time.Duration representing the difference between them:
start := time.Now()
end := start.Add(2 * time.Hour)
difference := end.Sub(start) // Returns 2h0m0sThese methods make it simple to calculate deadlines, measure elapsed time, or schedule future events. The original time.Time object remains unchanged - both methods return new values, following Go's preference for immutable operations.
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 project deadline calculator that uses time arithmetic to determine project milestones and deadlines. This challenge will test your ability to use the Add and Sub methods on time.Time objects to calculate future dates and time differences between events.
You will receive two inputs:
- A string containing project start information in the format
"year:month:day:hour:minute"(e.g.,"2024:1:15:9:0") - A string containing task durations in the format
"task1:duration_value:duration_unit,task2:duration_value:duration_unit"(e.g.,"Planning:5:Day,Development:3:Week,Testing:10:Day")
Your task is to:
- Parse the first input by splitting on colons to extract year, month, day, hour, and minute values
- Convert these string values to integers and create a project start time using
time.Date(usetime.UTCfor location, 0 for seconds and nanoseconds) - Parse the second input by splitting on commas to get individual task entries
- For each task entry, split on colons to extract task name, duration value, and duration unit
- Convert duration values to integers and create
time.Durationobjects using appropriate constants:- For
"Day": multiply by24 * time.Hour - For
"Week": multiply by7 * 24 * time.Hour - For
"Hour": multiply bytime.Hour
- For
- Display the application header:
"=== PROJECT DEADLINE CALCULATOR ===" - Display the project start:
"Project start time: [start_time_object]" - Calculate task deadlines by adding each task duration to the previous task's end time (first task starts at project start time):
- For each task, display:
"Task: [task_name]"" Duration: [duration_object]"" Start: [task_start_time]"" End: [task_end_time]"(calculated usingAddmethod)
- Calculate and display project timeline:
"=== PROJECT TIMELINE ===""Project start: [start_time_object]""Project end: [final_task_end_time]""Total project duration: [total_duration_object]"(calculated usingSubmethod between project end and start)
- Display task analysis:
"=== TASK ANALYSIS ===""Number of tasks: [number_of_tasks]""Longest task: [longest_task_name] ([longest_duration_object])""Shortest task: [shortest_task_name] ([shortest_duration_object])"
- Calculate time between consecutive tasks and display gaps:
"=== TASK TRANSITIONS ==="- For each pair of consecutive tasks:
"[first_task_name] to [second_task_name]: [time_difference_object]"(should be 0 since tasks are consecutive)
- Display project statistics:
"=== PROJECT STATISTICS ===""Total working days: [total_duration_in_hours_divided_by_24]""Total working hours: [total_duration_in_hours]""Project spans [number_of_calendar_days] calendar days"
- Display the completion message:
"Project timeline calculation completed successfully"
Use the time package for time operations, the strings package to split input strings, the strconv package to convert strings to integers, and the fmt package for formatted output. Remember that the Add method returns a new time.Time object representing the original time plus the duration, and the Sub method returns a time.Duration representing the difference between two times. This challenge demonstrates how to build a complete project timeline using time arithmetic operations.
Cheat sheet
Go provides two essential methods for time arithmetic: Add and Sub.
The Add method takes a time.Duration and returns a new time.Time:
now := time.Now()
tomorrow := now.Add(24 * time.Hour)The Sub method subtracts one time.Time from another and returns a time.Duration:
start := time.Now()
end := start.Add(2 * time.Hour)
difference := end.Sub(start) // Returns 2h0m0sBoth methods return new values without modifying the original time.Time object.
Try it yourself
package main
import (
"fmt"
"strconv"
"strings"
"time"
)
func main() {
// Read input
var startInfo string
var taskInfo string
fmt.Scanln(&startInfo)
fmt.Scanln(&taskInfo)
// Parse start time information
startParts := strings.Split(startInfo, ":")
year, _ := strconv.Atoi(startParts[0])
month, _ := strconv.Atoi(startParts[1])
day, _ := strconv.Atoi(startParts[2])
hour, _ := strconv.Atoi(startParts[3])
minute, _ := strconv.Atoi(startParts[4])
// Create project start time
startTime := time.Date(year, time.Month(month), day, hour, minute, 0, 0, time.UTC)
// Parse task information
taskEntries := strings.Split(taskInfo, ",")
// TODO: Write your code below
// - Process each task entry to extract name, duration value, and unit
// - Create duration objects for each task
// - Calculate task start and end times
// - Find longest and shortest tasks
// - Calculate project statistics
// - Display all required output sections
// Output will be generated by your implementation above
}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 Task7Error Handling In-Depth
Custom Error TypesWrapping Errors with `%w`Unwrapping with `errors.Is`Unwrapping with `errors.As`Understanding `panic`Using `recover`Recap - Safe Division10Working with Time
Getting the Current TimeCreating a Specific TimeFormatting TimeParsing Time StringsTime DurationTime ArithmeticSleeping and TickersRecap - Simple Timer2Structs 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