Last active
January 28, 2022 14:19
-
-
Save dfritschy/8d197be3d68021d0c0ae249a9b0a4b59 to your computer and use it in GitHub Desktop.
Go time.Time type with custom format for UnmarshalJSON and MarshalJSON
This file contains 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
// 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