Created
March 21, 2018 03:10
-
-
Save as/feb33be061cfff89497f4898542b92b5 to your computer and use it in GitHub Desktop.
How to compare time correctly in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
t0 := time.Now() | |
t1 := t0 | |
t2, _ := time.Parse(time.RFC3339, t0.Format(time.RFC3339)) | |
fmt.Println("incorrect (ignores monotonic clock)") | |
for i, t := range []time.Time{t0, t1, t2} { | |
fmt.Printf("t0(%v), t%d(%v), equal=%v\n", t0, i, t, t0 == t) | |
} | |
fmt.Println("correct (truncated monotonic clock)") | |
for i, t := range []time.Time{t0, t1, t2} { | |
t0 := t0.Round(0) | |
t = t0.Round(0) | |
fmt.Printf("t0(%v), t%d(%v), equal=%v\n", t0, i, t, t0 == t) | |
} | |
fmt.Println("correct (truncated second)") | |
for i, t := range []time.Time{t0, t1, t2} { | |
t0 := t0.Round(time.Second) | |
t = t.Add(time.Millisecond) | |
t = t0.Round(time.Second) | |
fmt.Printf("t0(%v), t%d(%v), equal=%v\n", t0, i, t, t0 == t) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment