Source From Here
Question
I have two time.Time objects and I want to get the difference between the two in terms of hours/minutes/seconds. Lets say:
- t1 = 2016-09-09 19:09:16 +0530 IST
- t2 = 2016-09-09 19:09:16 +0530 IST
In above case, since the difference is 0. It should give me 00:00:00. Consider another case:
- t1 = 2016-09-14 14:12:48 +0530 IST
- t2 = 2016-09-14 14:18:29 +0530 IST
In this case, difference would be 00:05:41.
How-To
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":
- 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:
If you want the time format HH:mm:ss, you may constuct a time.Time value and use its Time.Format() method like this:
- diff := t2.Sub(t1)
- out := time.Time{}.Add(diff)
- fmt.Println(out.Format("15:04:05"))
Ouptut:
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 (golang time.Since() with months and years) for details. 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).
沒有留言:
張貼留言