Skip to content

Instantly share code, notes, and snippets.

@literadix
Forked from uudashr/json.go
Created May 22, 2019 13:43
Show Gist options
  • Save literadix/2ae27c9a6053dcee6377b4b14171ffc4 to your computer and use it in GitHub Desktop.
Save literadix/2ae27c9a6053dcee6377b4b14171ffc4 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