Skip to content

Instantly share code, notes, and snippets.

@dfritschy
Last active January 28, 2022 14:19
Show Gist options
  • Save dfritschy/8d197be3d68021d0c0ae249a9b0a4b59 to your computer and use it in GitHub Desktop.
Save dfritschy/8d197be3d68021d0c0ae249a9b0a4b59 to your computer and use it in GitHub Desktop.
Go time.Time type with custom format for UnmarshalJSON and MarshalJSON
// JsonDate reflects the date format "yyyy-mm-dd" used in the API and the calendar component in the frontend.
type JsonDate time.Time
// UnmarshalJSON parses json dates
func (j *JsonDate) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), "\"")
t, err := time.Parse("2006-01-02", s)
if err != nil {
return err
}
*j = JsonDate(t)
return nil
}
// MarshalJSON outputs json dates
func (j *JsonDate) MarshalJSON() ([]byte, error) {
return []byte("\"" + j.Format("2006-01-02") + "\""), nil
}
// Format json dates
func (j JsonDate) Format(s string) string {
t := time.Time(j)
return t.Format(s)
}
// String returns json dates in printable form
func (j JsonDate) String() string {
return j.Format("2006-01-02")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment