Time Formatting in Go XML Unmarshal for time.Time Fields
Unmarshaling XML data into Go structs can sometimes encounter challenges when encountering date fields with non-default formats. This article addresses the issue of parsing dates without relying on string conversion.
Consider the sample struct Transaction, which includes a DateEntered field of type time.Time. The API returning the XML data uses a "yyyymmdd" date format, which is different from the default format used by time.Time.
Unfortunately, time.Time does not implement the xml.Unmarshaler interface, preventing direct specification of a custom date format. To overcome this limitation, a custom struct can be created with an anonymous time.Time field and custom UnmarshalXML implementation:
type Transaction struct { // ... DateEntered customTime `xml:"enterdate"` // use your own type that satisfies UnmarshalXML // ... } type customTime struct { time.Time } func (c *customTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { const shortForm = "20060102" // yyyymmdd date format var v string d.DecodeElement(&v, &start) parse, err := time.Parse(shortForm, v) if err != nil { return err } *c = customTime{parse} return nil }
By implementing UnmarshalXML, the customTime type can handle the custom "yyyymmdd" date format and store the parsed value in the anonymous time.Time field within the parent Transaction struct.
This approach ensures that dates are parsed and stored in the correct time.Time format without the need for manual string conversion or relying on default parsing assumptions.
The above is the detailed content of How to Unmarshal XML Date Strings into Time.Time Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!