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.

🎓

Subscribe to my Newsletter and Keep Learning.

Gain access to more content and get notified of the latest articles:

I send emails every 1-2 weeks and will keep your data safe. You can unsubscribe at any time.

Hello! I'm the Willem behind willem.dev

I created this website to help new Go developers, I hope it brings you some value! :)

You can follow me on Mastodon, Twitter/X or LinkedIn.

Thanks for reading!