droyo / go-xml

utility and code-generation libraries for XML
MIT License
304 stars 115 forks source link

Timezone is not considered in MarshalText method #113

Closed shmsr closed 4 years ago

shmsr commented 4 years ago

This code block is taken from the output generated by xsdgen:

func (t *xsdDateTime) UnmarshalText(text []byte) error {
    return _unmarshalTime(text, (*time.Time)(t), "2006-01-02T15:04:05.999999999")
}

func (t xsdDateTime) MarshalText() ([]byte, error) {
    return []byte((time.Time)(t).Format("2006-01-02T15:04:05.999999999")), nil
}

func _unmarshalTime(text []byte, t *time.Time, format string) (err error) {
    s := string(bytes.TrimSpace(text))
    *t, err = time.Parse(format, s)
    if _, ok := err.(*time.ParseError); ok {
        *t, err = time.Parse(format+"Z07:00", s)
    }
    return err
}

_unmarshalTime function is called when the UnmarshalText method is used which takes care of the parsing the timezone from the input. But MarshalText doesn't consider the timezone and hence ignored.

Example

With the MarshalText method generated by xsdgen, it does the marshalling without the timezone:

<granPeriod endTime="2020-03-26T12:30:00"></granPeriod>

But suppose if Z07:00 is added to MarshalText method:

func (t xsdDateTime) MarshalText() ([]byte, error) {
    return []byte((time.Time)(t).Format("2006-01-02T15:04:05.999999999Z07:00")), nil
}

Then it properly considers the timezone when marshalling:

<granPeriod endTime="2020-03-26T12:30:00-05:00"></granPeriod>
shmsr commented 4 years ago

Would you accept a PR? I'd like to fix this bug.

droyo commented 4 years ago

Yes, please file a PR. Thanks for reporting this!

shmsr commented 4 years ago

@droyo I've added a commit that fixes this bug. Could you please review it? And really sorry for being this late.

shmsr commented 4 years ago

@droyo Did you get a chance to review this? This is just a reminder!