Created
March 30, 2017 13:51
-
-
Save uudashr/6b285cf0c44b0a7375d1b786967e1712 to your computer and use it in GitHub Desktop.
Custom JSON time.Time format
This file contains hidden or 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
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