Difference between two times in hours, minutes or seconds

Avatar of the author Willem Schots
12 Feb, 2024
~2 min.
RSS

When working with time there are situations where you need to know the difference between two time instants.

The difference will tell you how much time has passed between the two time instants and the ordering of the time instants.

In Go, this difference can be obtained by calling the Sub method on a time.Time value. Calling t1.Sub(t2) will calculate the difference t1-t2.

This method will return a time.Duration as a result. The time.Duration type represents 1 nanosecond, if you want to get the time in a different resolution like seconds, hours or days you can use the different conversion methods on it.

See the example below.

main.go
package main

import (
	"fmt"
	"time"
)

func main() {
	t1 := time.Date(2024, 2, 8, 13, 37, 11, 0, time.UTC)
	t2 := time.Date(2024, 2, 8, 13, 36, 11, 0, time.UTC)

	diff := t1.Sub(t2)

	// Print hours, minutes and seconds
	fmt.Printf("%.3fh\n", diff.Hours())
	fmt.Printf("%.1fmin\n", diff.Minutes())
	fmt.Printf("%.0fs\n", diff.Seconds())

	// time.Duration by default formats pretty nicely.
	fmt.Printf("as string: %s\n", diff)
}

Negative difference

Calling t1.Sub(t2) when t2 is greater (later) than t1 will result in a negative duration. If you switch t1 and t2 in the example above, you can see this for yourself.

This works the same as when you’re subtracting numbers. For example: 2-3=-1 or 5-8=-3.

Location

The Sub method calculates the difference between time instants represented by the time.Time values. It takes into account the location (the time zone etc) used by the time.Time value. See the example below.

main.go
package main

import (
	"fmt"
	"time"
)

func main() {
	eastOfUTC := time.FixedZone("UTC+1", 60*60)
	t1 := time.Date(2024, 2, 8, 13, 37, 11, 0, eastOfUTC)
	t2 := time.Date(2024, 2, 8, 13, 37, 11, 0, time.UTC)

	diff := t2.Sub(t1)
	fmt.Println(diff)
}

As you can see, there is a difference of 1h0m0s eventhough both t1 and t2 contain the same clock reading.

Monotonic clock

If both time.Time values have a monotonic element, the monotonic clock element will be used to calculate the difference.

Make privacy claims you can back up

Join 800+ subscribers.
One email every few weeks.

I share what I learn building privacy-friendly systems. From confidential computing to Verbond and the occasional Go tip or trick. You can unsubscribe at any time.

A photo of Willem

Written by Willem Schots

I help teams prove what happens to their users' data, and I'm building Verbond, which shows where data can go before third-party code runs.

This site started as a place to learn Go. Most posts are now about privacy-friendly and verifiable systems, with the occasional Go post in between.

Want to talk about your system? Book a 30-minute call, or follow me on Bluesky and LinkedIn.