Last active
August 14, 2024 14:14
-
-
Save lummie/2cd6240378372079a8be7df782b380fc to your computer and use it in GitHub Desktop.
Golang custom date / time formats when marshalling to JSON
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
// CustomTime provides an example of how to declare a new time Type with a custom formatter. | |
// Note that time.Time methods are not available, if needed you can add and cast like the String method does | |
// Otherwise, only use in the json struct at marshal/unmarshal time. | |
type CustomTime time.Time | |
const ctLayout = "2006-01-02 15:04:05 Z07:00" | |
// UnmarshalJSON Parses the json string in the custom format | |
func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) { | |
s := strings.Trim(string(b), `"`) | |
nt, err := time.Parse(ctLayout, s) | |
*ct = CustomTime(nt) | |
return | |
} | |
// MarshalJSON writes a quoted string in the custom format | |
func (ct CustomTime) MarshalJSON() ([]byte, error) { | |
return []byte(ct.String()), nil | |
} | |
// String returns the time in the custom format | |
func (ct *CustomTime) String() string { | |
t := time.Time(*ct) | |
return fmt.Sprintf("%q", t.Format(ctLayout)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you