Skip to content

Instantly share code, notes, and snippets.

@dhermes
Last active April 11, 2024 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhermes/e30c1ec7e89f875631bb351f42d94755 to your computer and use it in GitHub Desktop.
Save dhermes/e30c1ec7e89f875631bb351f42d94755 to your computer and use it in GitHub Desktop.
[2024-04-11] Quirks of time in Go with `time.Local`, eng blog post?

Came up in hardfinhq/go-date#13

Consider

package main

import (
	"fmt"
	"os"
	"time"
)

func run() error {
	t1, err := time.Parse(time.RFC3339Nano, "2024-04-11T00:00:00.000-05:00")
	if err != nil {
		return err
	}

	t2 := t1.AddDate(0, -3, 0)
	fmt.Printf(
		"TZ = %q\nt1 = %q (%s)\nt2 = %q (%s)\n", os.Getenv("TZ"),
		t1, t1.UTC().Format(time.RFC3339Nano), t2, t2.UTC().Format(time.RFC3339Nano),
	)

	return nil
}

func main() {
	err := run()
	if err != nil {
		panic(err)
	}
}

Run it in different timezones and it behaves differently:

$ TZ=UTC go run ./m2/main.go
TZ = "UTC"
t1 = "2024-04-11 00:00:00 -0500 -0500" (2024-04-11T05:00:00Z)
t2 = "2024-01-11 00:00:00 -0500 -0500" (2024-01-11T05:00:00Z)
$ TZ=America/Chicago go run ./m2/main.go
TZ = "America/Chicago"
t1 = "2024-04-11 00:00:00 -0500 CDT" (2024-04-11T05:00:00Z)
t2 = "2024-01-11 00:00:00 -0600 CST" (2024-01-11T06:00:00Z)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment