Skip to content

Instantly share code, notes, and snippets.

@tonidy
Forked from lokeb/ISODate.go
Created May 11, 2022 23:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonidy/b571f97f600b33821418283f04f7d241 to your computer and use it in GitHub Desktop.
Save tonidy/b571f97f600b33821418283f04f7d241 to your computer and use it in GitHub Desktop.
Custom Date type with format YYYY-MM-DD and JSON decoder (Parser) and encoder (Unmarshal and Marshal methods)
//ISODate struct
type ISODate struct {
Format string
time.Time
}
//UnmarshalJSON ISODate method
func (Date *ISODate) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
Date.Format = "2006-01-02"
t, _ := time.Parse(Date.Format, s)
Date.Time = t
return nil
}
// MarshalJSON ISODate method
func (Date ISODate) MarshalJSON() ([]byte, error) {
return json.Marshal(Date.Time.Format(Date.Format))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment