如何在Go中将自定义格式的时间序列化到xml中/从xml序列化?

问题描述:

When serializing a datetime to/from xml how do I make it use a custom time format?

将日期时间从xml序列化到/从xml序列化时,如何使用自定义时间格式? p> \ n div>

Just as you'd implement json.Marshaler and json.Unmarshaler for doing this with JSON (there are many posts about that on StackOverflow and the internet); one way is to implement a custom time type that implements encoding.TextMarshaler and encoding.TextUnmarshaler.

Those interfaces are used by encoding/xml when encoding items (after first checking for the more specific xml.Marshaler or xml.Unmarshaler interfaces, however those later ones have to do full XML encoding themselves).

E.g. something like (full example on the Go Playground):

const fixedFormat = "Mon Jan 02 2006"

type myTime1 struct {
    time.Time
}

func (m myTime1) MarshalText() ([]byte, error) {
    text := m.Time.Format(fixedFormat)
    return []byte(text), nil
}
func (m *myTime1) UnmarshalText(text []byte) error {
    t, err := time.Parse(fixedFormat, string(text))
    if err == nil {
        m.Time = t
    }
    return err
}

or

type myTime2 time.Time

func (m myTime2) MarshalText() ([]byte, error) {
    text := time.Time(m2).Format(fixedFormat)
    return []byte(text), nil
}
func (m *myTime2) UnmarshalText(text []byte) error {
    t, err := time.Parse(fixedFormat, string(text))
    if err == nil {
        *m = myTime2(t)
    }
    return err
}

Either of those can be used in place of time.Time as part of a larger data structure used with xml (un)marshalling. E.g.:

type Foo struct {
    Date1 myTime1 `xml:"date1"`
    Date2 myTime2 `xml:"date2"`
}

The difference in how these custom time types are defined changes how you use them with regular time.Time values. E.g.

m1 := myTime1{time.Now()}
fmt.Println(m1)
if m1.Before(time.Now()) {}
t1 := m1.Time
// compared to:
m2 := myTime2(time.Now())
fmt.Println(time.Time(m2))
if time.Time(m2).Before(time.Now()) {}
t2 := time.Time(m2)

It depends how your format looks like, but a good starting point should be the time library. http://golang.org/pkg/time/

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)