Last active
December 23, 2022 04:39
-
-
Save mecitsemerci/6517ae38a4355ad44bf695d89c76a242 to your computer and use it in GitHub Desktop.
Golang json (un)marshal custom date formats
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
package customTypes | |
import ( | |
"errors" | |
"fmt" | |
"strings" | |
"time" | |
) | |
type JSONTime time.Time | |
const DefaultFormat = time.RFC3339 | |
var layouts = []string{ | |
DefaultFormat, | |
"2006-01-02T15:04Z", // ISO 8601 UTC | |
"2006-01-02T15:04:05Z", // ISO 8601 UTC | |
"2006-01-02T15:04:05.000Z", // ISO 8601 UTC | |
"2006-01-02T15:04:05", // ISO 8601 UTC | |
"2006-01-02 15:04", // Custom UTC | |
"2006-01-02 15:04:05", // Custom UTC | |
"2006-01-02 15:04:05.000", // Custom UTC | |
} | |
// JSONTime | |
func (jt *JSONTime) String() string { | |
t := time.Time(*jt) | |
return t.Format(DefaultFormat) | |
} | |
func (jt JSONTime) MarshalJSON() ([]byte, error) { | |
return []byte(fmt.Sprintf(`"%s"`,jt.String())), nil | |
} | |
func (jt *JSONTime) UnmarshalJSON(b []byte) error { | |
timeString := strings.Trim(string(b), `"`) | |
for _, layout := range layouts { | |
t, err := time.Parse(layout, timeString) | |
if err == nil { | |
*jt = JSONTime(t) | |
return nil | |
} | |
} | |
return errors.New(fmt.Sprintf("Invalid date format: %s", timeString)) | |
} | |
func (jt *JSONTime) ToTime() time.Time { | |
return time.Time(*jt) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks buddy!