Created
October 27, 2017 01:19
-
-
Save maxp/300910ba17386f69a8a4b046dadcb1e8 to your computer and use it in GitHub Desktop.
How to handle custom time formats in json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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