From 7113cf9406518bb931cd4f759c2181764b861941 Mon Sep 17 00:00:00 2001 From: Chad Kunde Date: Fri, 1 Jul 2022 23:29:35 +0800 Subject: [PATCH] configure default location for time parsing Interacting with servers that utilize the ISO-8601 Local Time variants in request and response payloads can configure the request marshaling using NormalizeTimeForMarshal setting, but don't have a ready method for setting the local time zone when parsing the response fields. Keep UTC as the default location, to maintain the previous functionality. Signed-off-by: Chad Kunde --- date.go | 6 +++--- format.go | 2 +- time.go | 5 ++++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/date.go b/date.go index f0b3109..3c93381 100644 --- a/date.go +++ b/date.go @@ -57,7 +57,7 @@ func (d *Date) UnmarshalText(text []byte) error { if len(text) == 0 { return nil } - dd, err := time.Parse(RFC3339FullDate, string(text)) + dd, err := time.ParseInLocation(RFC3339FullDate, string(text), DefaultTimeLocation) if err != nil { return err } @@ -107,7 +107,7 @@ func (d *Date) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &strdate); err != nil { return err } - tt, err := time.Parse(RFC3339FullDate, strdate) + tt, err := time.ParseInLocation(RFC3339FullDate, strdate, DefaultTimeLocation) if err != nil { return err } @@ -126,7 +126,7 @@ func (d *Date) UnmarshalBSON(data []byte) error { } if data, ok := m["data"].(string); ok { - rd, err := time.Parse(RFC3339FullDate, data) + rd, err := time.ParseInLocation(RFC3339FullDate, data, DefaultTimeLocation) if err != nil { return err } diff --git a/format.go b/format.go index 172055d..ad3b3c3 100644 --- a/format.go +++ b/format.go @@ -109,7 +109,7 @@ func (f *defaultFormats) MapStructureHookFunc() mapstructure.DecodeHookFunc { // if to == tpe { switch v.Name { case "date": - d, err := time.Parse(RFC3339FullDate, data) + d, err := time.ParseInLocation(RFC3339FullDate, data, DefaultTimeLocation) if err != nil { return nil, err } diff --git a/time.go b/time.go index 023676e..921e712 100644 --- a/time.go +++ b/time.go @@ -86,6 +86,9 @@ var ( // NormalizeTimeForMarshal provides a normalization function on time befeore marshalling (e.g. time.UTC). // By default, the time value is not changed. NormalizeTimeForMarshal = func(t time.Time) time.Time { return t } + + // DefaultTimeLocation provides a location for a time when the time zone is not encoded in the string (ex: ISO8601 Local variants). + DefaultTimeLocation = time.UTC ) // ParseDateTime parses a string that represents an ISO8601 time or a unix epoch @@ -95,7 +98,7 @@ func ParseDateTime(data string) (DateTime, error) { } var lastError error for _, layout := range DateTimeFormats { - dd, err := time.Parse(layout, data) + dd, err := time.ParseInLocation(layout, data, DefaultTimeLocation) if err != nil { lastError = err continue