Calculate the time difference between two Go time.Time values by subtracting the earlier time from the later one using the Sub() method.
Subtract the earlier time.Time value from the later one using the .Sub() method to get a time.Duration.
package main
import (
"fmt"
"time"
)
func main() {
t1 := time.Now()
time.Sleep(2 * time.Second)
t2 := time.Now()
duration := t2.Sub(t1)
fmt.Println(duration) // e.g., 2.000123456s
}
Calculating the difference between two times in Go determines the exact duration between two moments. Think of it like subtracting a start time from an end time on a stopwatch to see how long an event took. You use this whenever you need to measure performance or track elapsed time.