How to Unmarshal Inconsistent Datetime Formats in Go?

Barbara Streisand
Release: 2024-11-05 05:31:01
Original
744 people have browsed it

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"`
}
Copy after login

In this custom unmarshaling method (UnmarshalJSON), we:

  1. Parse using the standard RFC3339Nano format.
  2. If parsing fails due to incorrect timezone offset format, we parse using a modified format ("2006-01-02T15:04:05.999999999Z0700") that inserts a ':' into the timezone offset.

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template