Menu
Coddy logo textTech

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 2h0m0s

These 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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create 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:

  1. Parse the first input by splitting on colons to extract year, month, day, hour, and minute values
  2. Convert these string values to integers and create a project start time using time.Date (use time.UTC for location, 0 for seconds and nanoseconds)
  3. Parse the second input by splitting on commas to get individual task entries
  4. For each task entry, split on colons to extract task name, duration value, and duration unit
  5. Convert duration values to integers and create time.Duration objects using appropriate constants:
    • For "Day": multiply by 24 * time.Hour
    • For "Week": multiply by 7 * 24 * time.Hour
    • For "Hour": multiply by time.Hour
  6. Display the application header: "=== PROJECT DEADLINE CALCULATOR ==="
  7. Display the project start: "Project start time: [start_time_object]"
  8. Calculate task deadlines by adding each task duration to the previous task's end time (first task starts at project start time):
  9. For each task, display:
    • "Task: [task_name]"
    • " Duration: [duration_object]"
    • " Start: [task_start_time]"
    • " End: [task_end_time]" (calculated using Add method)
  10. 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 using Sub method between project end and start)
  11. 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])"
  12. 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)
  13. 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"
  14. 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 2h0m0s

Both 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
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow