2020年11月6日 星期五

[ 常見問題 ] Difference between two time.Time objects

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:

  1. t1 = 2016-09-09 19:09:16 +0530 IST  
  2. 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:

  1. t1 = 2016-09-14 14:12:48 +0530 IST  
  2. 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":

  1. package main  
  2.   
  3. import (  
  4.     "fmt"  
  5.     "time"  
  6. )  
  7.   
  8. func main() {  
  9.     t1 := time.Now()  
  10.     t2 := t1.Add(time.Second * 341)  
  11.   
  12.     fmt.Println(t1)  
  13.     fmt.Println(t2)  
  14.   
  15.     diff := t2.Sub(t1)  
  16.     fmt.Println(diff)  
  17. }  

Output:

2020-11-06 19:58:39.0127867 +0800 CST m=+0.002991401
2020-11-06 20:04:20.0127867 +0800 CST m=+341.002991401
5m41s

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

  1. diff := t2.Sub(t1)  
  2. out := time.Time{}.Add(diff)  
  3. fmt.Println(out.Format("15:04:05"))  

Ouptut:

00:05:41


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:

  1. 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).

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...