Skip to content

Instantly share code, notes, and snippets.

@mecitsemerci
Last active December 23, 2022 04:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mecitsemerci/6517ae38a4355ad44bf695d89c76a242 to your computer and use it in GitHub Desktop.
Save mecitsemerci/6517ae38a4355ad44bf695d89c76a242 to your computer and use it in GitHub Desktop.
Golang json (un)marshal custom date formats
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)
}
@eriknyk
Copy link

eriknyk commented Dec 23, 2022

Thanks buddy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment