Home >Backend Development >Golang >How to Unmarshal Inconsistent Datetime Formats in Go?
Unmarshal Inconsistent Datetime Formats
When dealing with JSON data, unmarshaling datetimes can lead to inconsistencies due to varying timezone offset formats. While Go's standard parsing mechanism expects timezone offsets in the format 02:00, some data may contain incorrect formats such as 0200.
To address this, Go provides a custom unmarshaling method to handle both correct and incorrect timezone formats. Here's a revised approach:
type MyTime struct { time.Time } func (self *MyTime) UnmarshalJSON(b []byte) (err error) { s := string(b) // Remove quotation marks s = s[1:len(s)-1] // Attempt to parse using RFC3339Nano format t, err := time.Parse(time.RFC3339Nano, s) if err != nil { // If parsing fails, try custom format without ':' t, err = time.Parse("2006-01-02T15:04:05.999999999Z0700", s) } self.Time = t return } type Test struct { Time MyTime `json:"time"` }
In this custom unmarshaling method (UnmarshalJSON), we:
This approach ensures that both correct and incorrectly formatted datetime strings are parsed correctly.
The above is the detailed content of How to Unmarshal Inconsistent Datetime Formats in Go?. For more information, please follow other related articles on the PHP Chinese website!