Created
April 14, 2023 13:04
-
-
Save stvoidit/f91a746b901f6efe2e0f22fda5773b7d to your computer and use it in GitHub Desktop.
custom date time type for JSON
This file contains hidden or 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
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