How to serialize a custom formatted time to/from xml in Go? -


when serializing datetime to/from xml how make use custom time format?

just you'd implement json.marshaler , json.unmarshaler doing json (there many posts on stackoverflow , internet); 1 way implement custom time type implements encoding.textmarshaler , encoding.textunmarshaler.

those interfaces used encoding/xml when encoding items (after first checking more specific xml.marshaler or xml.unmarshaler interfaces, later ones have full xml encoding themselves).

e.g. something (full example on 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 can used in place of time.time part of larger data structure used xml (un)marshalling. e.g.:

type foo struct {     date1 mytime1 `xml:"date1"`     date2 mytime2 `xml:"date2"` } 

the difference in how these custom time types defined changes how use them 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) 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -