Created
April 14, 2025 08:15
-
-
Save erdnaxeli/ce05bc13a8803e33b986932c35c8ade4 to your computer and use it in GitHub Desktop.
pitfalls in go time library?
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() { | |
now := time.Now() | |
// Include timezone and utc offset | |
fmt.Println(now) | |
paris, _ := time.LoadLocation("Europe/Paris") | |
fmt.Println(paris) | |
bedtime := time.Date(2023, 3, 25, 22, 0, 0, 0, paris) | |
wakeUp := time.Date(2023, 3, 26, 7, 0, 0, 0, paris) | |
sleep := wakeUp.Sub(bedtime) | |
// Correct: 8h | |
fmt.Printf("sleep: %s\n", sleep) | |
// Behavior not well-defined (here it takes the date in CET) | |
d := time.Date(2023, 3, 26, 2, 30, 0, 0, paris) | |
// It prints it in CEST, so 3h30 | |
fmt.Println(d) | |
// Correct: disambiguation does not break equality | |
timestamp := d.Unix() | |
parsedTimestamp := time.Unix(timestamp, 0) | |
fmt.Printf("%s == %s = %t\n", parsedTimestamp, d, parsedTimestamp.Equal(d)) | |
my_tz := time.Date(2023, 1, 1, 0, 0, 0, 0, paris).Local().Location() | |
// Just print "Local" | |
fmt.Printf("my_tz: %s\n", my_tz) | |
// Correct: infer the date in CEST | |
fmt.Println(time.Date(2023, 7, 1, 0, 0, 0, 0, my_tz)) | |
// output: | |
// | |
// 2025-04-14 10:12:08.856505473 +0200 CEST m=+0.000020762 | |
// Europe/Paris | |
// sleep: 8h0m0s | |
// 2023-03-26 03:30:00 +0200 CEST | |
// 2023-03-26 03:30:00 +0200 CEST == 2023-03-26 03:30:00 +0200 CEST = true | |
// my_tz: Local | |
// 2023-07-01 00:00:00 +0200 CEST | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment