Go's JSON unmarshaling has issues with datetimes formatted according to ISO8601/RFC3339 that have timezone offsets in the format 0200 instead of 02:00.
Incorrect JSON Format:
2016-08-08T21:35:14.052975+0200
Expected Correct Format:
2016-08-08T21:35:14.052975+02:00
Possible Cause:
The JSON was generated using C's strftime function with a format string that does not include the colon in the timezone offset.
To resolve this issue and enable the correct unmarshalling of both formats, a custom time field type can be defined:
<code class="go">type MyTime struct { time.Time } func (self *MyTime) UnmarshalJSON(b []byte) (err error) { s := string(b) // Remove double quotes from JSON value s = s[1:len(s)-1] t, err := time.Parse(time.RFC3339Nano, s) if err != nil { t, err = time.Parse("2006-01-02T15:04:05.999999999Z0700", s) } self.Time = t return }</code>
In this custom type, the UnmarshalJSON method attempts to parse the string according to both RFC3339Nano (with a colon in the timezone offset) and a modified version of RFC3339Nano without the colon.
To use the custom time field type:
<code class="go">type Test struct { Time MyTime `json:"time"` }</code>
This struct can then be unmarshalled from either JSON format with the incorrect or correct timezone offset.
The above is the detailed content of How to Unmarshal JSON with Incorrect Timezone Offset in Go?. For more information, please follow other related articles on the PHP Chinese website!