Go

What does this print? Explain the monotonic clock and time.Time comparison.

Question 463HardGo 1.22 to 1.25
t1 := time.Now()
t2 := t1.Round(0) // strips monotonic reading
fmt.Println(t1 == t2, t1.Equal(t2))

loc, _ := time.LoadLocation("Asia/Kolkata")
t3 := t2.In(loc)
fmt.Println(t2 == t3, t2.Equal(t3))

m := map[time.Time]bool{t2: true}
fmt.Println(m[t3])

Output:

false true
false true
false

time.Now() returns a Time carrying both a wall clock and a monotonic clock reading. t.Sub, time.Since, Before/After use the monotonic part when both values have it, so elapsed-time measurement is immune to NTP adjustments or manual clock changes. Round(0), In, UTC, serialization and time.Date strip or lack it.

== compares the struct fields (wall, ext, location pointer), so the same instant with different monotonic data or different Location is "unequal". Always use t.Equal(u), and never use time.Time as a map key without normalizing (e.g. t.UTC().Round(0) or t.UnixNano()).

Related: store/transmit times in UTC, use time.RFC3339Nano, and remember the layout reference is Mon Jan 2 15:04:05 MST 2006 — "YYYY-MM-DD" is not a valid layout.

More on Standard Library, HTTP & Systems Design in Go

All 35 Standard Library, HTTP & Systems Design in Go questions