From 75446032b914bb0be5e07da29c976034c0a666cf Mon Sep 17 00:00:00 2001 From: Torkel Rogstad Date: Fri, 12 Mar 2021 14:42:51 +0100 Subject: [PATCH] Normalize UTC timestamps to comply with stdlib --- timestamptz.go | 22 ++++++++++++++++++++-- timestamptz_test.go | 6 ++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/timestamptz.go b/timestamptz.go index 299a866..5870197 100644 --- a/timestamptz.go +++ b/timestamptz.go @@ -124,7 +124,7 @@ func (dst *Timestamptz) DecodeText(ci *ConnInfo, src []byte) error { return err } - *dst = Timestamptz{Time: tim, Status: Present} + *dst = Timestamptz{Time: normalizePotentialUTC(tim), Status: Present} } return nil @@ -231,6 +231,9 @@ func (src Timestamptz) Value() (driver.Value, error) { if src.InfinityModifier != None { return src.InfinityModifier.String(), nil } + if src.Time.Location().String() == time.UTC.String() { + return src.Time.UTC(), nil + } return src.Time, nil case Null: return nil, nil @@ -289,8 +292,23 @@ func (dst *Timestamptz) UnmarshalJSON(b []byte) error { return err } - *dst = Timestamptz{Time: tim, Status: Present} + *dst = Timestamptz{Time: normalizePotentialUTC(tim), Status: Present} } return nil } + +// Normalize timestamps in UTC location to behave similarly to how the Golang +// standard library does it: UTC timestamps lack a .loc value. +// +// Reason for this: when comparing two timestamps with reflect.DeepEqual (generally +// speaking not a good idea, but several testing libraries (for example testify) +// does this), their location data needs to be equal for them to be considered +// equal. +func normalizePotentialUTC(timestamp time.Time) time.Time { + if timestamp.Location().String() != time.UTC.String() { + return timestamp + } + + return timestamp.UTC() +} diff --git a/timestamptz_test.go b/timestamptz_test.go index c3f6396..2ff326b 100644 --- a/timestamptz_test.go +++ b/timestamptz_test.go @@ -70,8 +70,7 @@ func TestTimestamptzNanosecondsTruncated(t *testing.T) { t.Errorf("%d. EncodeText failed - %v", i, err) } - tstz.DecodeText(nil, buf) - if err != nil { + if err := tstz.DecodeText(nil, buf); err != nil { t.Errorf("%d. DecodeText failed - %v", i, err) } @@ -87,8 +86,7 @@ func TestTimestamptzNanosecondsTruncated(t *testing.T) { t.Errorf("%d. EncodeBinary failed - %v", i, err) } - tstz.DecodeBinary(nil, buf) - if err != nil { + if err := tstz.DecodeBinary(nil, buf); err != nil { t.Errorf("%d. DecodeBinary failed - %v", i, err) }