Skip to content

Instantly share code, notes, and snippets.

@maxp
Created October 27, 2017 01:19
Show Gist options
  • Save maxp/300910ba17386f69a8a4b046dadcb1e8 to your computer and use it in GitHub Desktop.
Save maxp/300910ba17386f69a8a4b046dadcb1e8 to your computer and use it in GitHub Desktop.
How to handle custom time formats in json
type MyTime struct {
time.Time
}
func (self *MyTime) UnmarshalJSON(b []byte) (err error) {
s := string(b)
// Get rid of the quotes "" around the value.
// A second option would be to include them
// in the date format string instead, like so below:
// time.Parse(`"`+time.RFC3339Nano+`"`, s)
s = s[1:len(s)-1]
t, err := time.Parse(time.RFC3339Nano, s)
if err != nil {
t, err = time.Parse("2006-01-02T15:04:05.999999999Z0700", s)
}
self.Time = t
return
}
type Test struct {
Time MyTime `json:"time"`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment