Difference between two time.Time objects

You may use Time.Sub() to get the difference between the 2 time.Time values, result will be a value of time.Duration.

When printed, a time.Duration formats itself "intelligently":

t1 := time.Now()
t2 := t1.Add(time.Second * 341)


diff := t2.Sub(t1)


2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:05:41 +0000 UTC

If you want the time format HH:mm:ss, you may constuct a time.Time value and use its Time.Format() method like this:

out := time.Time{}.Add(diff)



Try the examples on the Go Playground.

Of course this will only work if the time difference is less than a day. If the difference may be bigger, then it's another story. The result must include days, months and years. Complexity increases significnatly. See this question for details:

golang time.Since() with months and years

The solution presented there solves this issue by showing a function with signature:

func diff(a, b time.Time) (year, month, day, hour, min, sec int)

You may use that even if your times are within 24 hours (in which case year, month and day will be 0).