Skip to content

Instantly share code, notes, and snippets.

@uudashr
Created March 30, 2017 13:51
Show Gist options
  • Save uudashr/6b285cf0c44b0a7375d1b786967e1712 to your computer and use it in GitHub Desktop.
Save uudashr/6b285cf0c44b0a7375d1b786967e1712 to your computer and use it in GitHub Desktop.
Custom JSON time.Time format
const jsonTimeLayout = "2006-01-02T15:04:05+07:00"
// JSONTime is the time.Time with JSON marshal and unmarshal capability
type JSONTime struct {
time.Time
}
// UnmarshalJSON will unmarshal using 2006-01-02T15:04:05+07:00 layout
func (t *JSONTime) UnmarshalJSON(b []byte) error {
parsed, err := time.Parse(jsonTimeLayout, string(b))
if err != nil {
return err
}
t.Time = parsed
return nil
}
// MarshalJSON will marshal using 2006-01-02T15:04:05+07:00 layout
func (t *JSONTime) MarshalJSON() ([]byte, error) {
s := t.Format(jsonTimeLayout)
return []byte(s), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment