]> Cypherpunks repositories - gostls13.git/commit
time: clarify docs to avoid date calculation pitfalls
authorBrendan Jackman <jackmanb@google.com>
Fri, 8 Sep 2023 07:46:19 +0000 (07:46 +0000)
committerGopher Robot <gobot@golang.org>
Tue, 3 Oct 2023 14:10:22 +0000 (14:10 +0000)
commit98289021f3444a2f80c8f7630f5e519d9c338963
treeff3ce0dfa6aa70361b7460c51787d69791bc7841
parent36b14a78b58924a8aea22c8949c3b8a4b7045d8b
time: clarify docs to avoid date calculation pitfalls

I recently reviewed some code that did time calculations using
`time.UnixMicro(0).UTC()`. I commented that because time calculations
are independent of the location, they should drop the `.UTC()`, and they
replied that it made their tests fail.

I looked into it and eventually discovered it was because they were
using AddDate. Dramatically simplified, their code did something like:

    orig := time.Date(2013, time.March, 23, 12, 00, 0, 0, time.UTC)
    want := time.Date(2013, time.March, 23, 0, 0, 0, 0, time.UTC)

    epoch := time.UnixMicro(0)

    days := int(orig.Sub(epoch).Hours() / 24)

    got := epoch.AddDate(0, 0, days)
    if !got.Equal(want) {
        t.Errorf("ay caramba: %v vs %v", got.UTC(), want.UTC())
    }

The issue is that their tests run in Pacific time, which is currently
PST (UTC-8) but was PDT (UTC-7) in January 1970.

It turns out they were implementing some business policy that really
cares abut calendar days so AddDate is correct, but it's certainly a bit
confusing!

The idea with this change is to remove the risk that readers make a
false shortcut in their mind: "Locations do not affect time
calculations". To do this we remove some text from the core time.Time
doc and shift it to the areas of the library that deal with these
intrinsically confusing operations.

Change-Id: I8200e9edef7d1cdd8516719e34814eb4b78d30a2
Reviewed-on: https://go-review.googlesource.com/c/go/+/526676
Reviewed-by: Ian Lance Taylor <iant@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Rob Pike <r@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
src/time/example_test.go
src/time/time.go
src/time/zoneinfo.go