Skip to content

Instantly share code, notes, and snippets.

@stvoidit
Created April 14, 2023 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stvoidit/f91a746b901f6efe2e0f22fda5773b7d to your computer and use it in GitHub Desktop.
Save stvoidit/f91a746b901f6efe2e0f22fda5773b7d to your computer and use it in GitHub Desktop.
custom date time type for JSON
type DateTime time.Time
const iso8601 = "2006-01-02 15:04:05Z07:00"
func (dt DateTime) AsTime() time.Time {
return time.Time(dt)
}
func (dt DateTime) Format(layout string) string {
return dt.AsTime().Format(layout)
}
func (dt DateTime) MarshalJSON() ([]byte, error) {
return []byte(dt.AsTime().Format(iso8601)), nil
}
func (dt *DateTime) UnmarshalJSON(b []byte) error {
t, err := time.Parse(iso8601, string(b))
if err != nil {
return err
}
*dt = DateTime(t)
return nil
}
func (dt DateTime) String() string {
return dt.AsTime().Format(iso8601)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment