Skip to content

Instantly share code, notes, and snippets.

@lummie
Last active April 7, 2024 21:34
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save lummie/2cd6240378372079a8be7df782b380fc to your computer and use it in GitHub Desktop.
Save lummie/2cd6240378372079a8be7df782b380fc to your computer and use it in GitHub Desktop.
Golang custom date / time formats when marshalling to JSON
// CustomTime provides an example of how to declare a new time Type with a custom formatter.
// Note that time.Time methods are not available, if needed you can add and cast like the String method does
// Otherwise, only use in the json struct at marshal/unmarshal time.
type CustomTime time.Time
const ctLayout = "2006-01-02 15:04:05 Z07:00"
// UnmarshalJSON Parses the json string in the custom format
func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) {
s := strings.Trim(string(b), `"`)
nt, err := time.Parse(ctLayout, s)
*ct = CustomTime(nt)
return
}
// MarshalJSON writes a quoted string in the custom format
func (ct CustomTime) MarshalJSON() ([]byte, error) {
return []byte(ct.String()), nil
}
// String returns the time in the custom format
func (ct *CustomTime) String() string {
t := time.Time(*ct)
return fmt.Sprintf("%q", t.Format(ctLayout))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment