How to Add or Subtract Time in Go with time.Duration

Use the `time.Duration` type to represent time intervals and add or subtract them from a `time.Time` value using the built-in `Add()` and `Sub()` methods.

Use the time.Duration type to represent time intervals and add or subtract them from a time.Time value using the built-in Add() and Sub() methods. These methods handle all calendar logic, including leap years and varying month lengths, automatically.

Here is a practical example showing how to manipulate time with durations:

package main

import (
	"fmt"
	"time"
)

func main() {
	// Start with a specific time
	now := time.Now()
	
	// Define durations using built-in constants or custom values
	oneHour := time.Hour
	threeDays := 3 * 24 * time.Hour
	negativeDuration := -45 * time.Minute

	// Add time to get a future timestamp
	future := now.Add(oneHour)
	
	// Subtract time by adding a negative duration
	past := now.Add(negativeDuration)
	
	// Alternatively, use Sub() to find the difference between two times
	// This returns a Duration representing the time elapsed
	diff := future.Sub(now)

	fmt.Printf("Current:     %s\n", now.Format(time.RFC3339))
	fmt.Printf("Future (+1h): %s\n", future.Format(time.RFC3339))
	fmt.Printf("Past (-45m):  %s\n", past.Format(time.RFC3339))
	fmt.Printf("Difference:   %v\n", diff)
}

You can also construct durations from strings using time.ParseDuration(), which is useful for configuration values or user input. This method parses strings like "1h30m" or "24h" into a time.Duration.

package main

import (
	"fmt"
	"time"
)

func main() {
	// Parse a string duration
	duration, err := time.ParseDuration("1h30m")
	if err != nil {
		fmt.Println("Error parsing duration:", err)
		return
	}

	start := time.Date(2023, 10, 27, 10, 0, 0, 0, time.UTC)
	end := start.Add(duration)

	fmt.Printf("Start: %s\n", start.Format("15:04:05"))
	fmt.Printf("End:   %s\n", end.Format("15:04:05"))
}

Key points to remember: time.Duration is a signed int64 representing nanoseconds, so arithmetic operations are straightforward. When subtracting two time.Time values, the result is always a time.Duration. Conversely, adding a time.Duration to a time.Time always results in a time.Time. Always check for errors when parsing durations from strings, as invalid formats will return an error.