Home > Backend Development > Golang > How to Unmarshal Incorrectly Formatted Datetime in Go?

How to Unmarshal Incorrectly Formatted Datetime in Go?

DDD
Release: 2024-11-07 21:48:03
Original
470 people have browsed it

How to Unmarshal Incorrectly Formatted Datetime in Go?

Unmarshalling Incorrectly Formatted Datetime

When encountering JSON with incorrectly formatted datetime fields, it becomes essential to devise a robust strategy to parse and unmarshal them into Go structs. The incorrect format typically involves an absence of the colon character ":" in the timezone offset, leading to unmarshalling errors.

Solution: Custom Type and UnmarshalJSON Method

To resolve this issue, a custom type can be defined to support both the correct and incorrect formats:

<code class="go">type MyTime struct {
    time.Time
}

func (self *MyTime) UnmarshalJSON(b []byte) (err error) {
    s := string(b)
    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>
Copy after login

When unmarshalling, this type's UnmarshalJSON method is invoked. It first removes the surrounding quotes from the JSON string. It then attempts to parse the datetime using the standard time.RFC3339Nano format. If that fails, it proceeds to try parsing using the incorrect format without the colon character ("2006-01-02T15:04:05.999999999Z0700").

Struct Definition

To use this custom type within a Go struct:

<code class="go">type Test struct {
    Time MyTime `json:"time"`
}</code>
Copy after login

This ensures that JSON with both correct and incorrect datetime formats can be unmarshalled into the same Go struct.

Conclusion

By defining a custom time field type with a suitable UnmarshalJSON method, it is possible to parse and unmarshal incorrectly formatted datetime fields seamlessly in Go programs. This allows for greater flexibility in handling input data and ensures that the Go struct representation accurately reflects the data, regardless of its format.

The above is the detailed content of How to Unmarshal Incorrectly Formatted Datetime in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template