How to Calculate the Difference Between Two Times in Go

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
}