When serializing a datetime to/from xml how do I make it use a custom time format?
How to serialize a custom formatted time to/from xml in Go?
897 views Asked by matt.s At
        	2
        	
        There are 2 answers
0
                
                        
                            
                        
                        
                            On
                            
                            
                                                    
                    
                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)
                        
Just as you'd implement
json.Marshalerandjson.Unmarshalerfor 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 implementsencoding.TextMarshalerandencoding.TextUnmarshaler.Those interfaces are used by
encoding/xmlwhen encoding items (after first checking for the more specificxml.Marshalerorxml.Unmarshalerinterfaces, however those later ones have to do full XML encoding themselves).E.g. something like (full example on the Go Playground):
or
Either of those can be used in place of
time.Timeas part of a larger data structure used with xml (un)marshalling. E.g.:The difference in how these custom time types are defined changes how you use them with regular
time.Timevalues. E.g.