Skip to content

Instantly share code, notes, and snippets.

@lokeb
Created September 9, 2018 19:00
Show Gist options
  • Save lokeb/7a7e2747dedcc5c5ff86f11f5f81d4aa to your computer and use it in GitHub Desktop.
Save lokeb/7a7e2747dedcc5c5ff86f11f5f81d4aa 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