Home >Backend Development >Golang >How to Calculate the Difference Between Two Time Instances in Go?
Determining Time Differences
You have two time.Time instances, and you need to calculate their difference in hours, minutes, and seconds. Consider the scenarios:
Solution
To calculate the difference, use the Time.Sub() function. The result is a time.Duration value.
Time.Duration prints itself intelligently:
package main import ( "fmt" "time" ) func main() { t1 := time.Now() t2 := t1.Add(time.Second * 341) fmt.Println(t1) fmt.Println(t2) diff := t2.Sub(t1) fmt.Println(diff) }
Output:
2009-11-10 23:00:00 +0000 UTC 2009-11-10 23:05:41 +0000 UTC 5m41s
For a time format of HH:mm:ss, construct a time.Time value and use its Time.Format() method:
out := time.Time{}.Add(diff) fmt.Println(out.Format("15:04:05"))
Output:
00:05:41
This works for time differences under 24 hours. For larger differences, consider using a solution that includes days, months, and years.
The above is the detailed content of How to Calculate the Difference Between Two Time Instances in Go?. For more information, please follow other related articles on the PHP Chinese website!