Skip to content

Instantly share code, notes, and snippets.

@peacefixation
Last active March 26, 2019 02:21
Show Gist options
  • Save peacefixation/d0cb355a7bd9ee342ee980e6d9160e2c to your computer and use it in GitHub Desktop.
Save peacefixation/d0cb355a7bd9ee342ee980e6d9160e2c to your computer and use it in GitHub Desktop.
Implement MarshalJSON and UnmarshalJSON on a custom type
import (
"fmt"
"strings"
"time"
)
const timeFormat = "2006-01-02 15:04:05"
// JSONTime a wrapper for time.Time that unmarshalls with a custom date format
type JSONTime struct {
time.Time // anonymous field, struct inherits methods, refer to instance.Time
}
// UnmarshalJSON unmarshal JSON field to a JSONTime
func (t *JSONTime) UnmarshalJSON(buf []byte) error {
tt, err := time.Parse(timeFormat, strings.Trim(string(buf), `"`))
if err != nil {
return err
}
t.Time = tt
return nil
}
// MarshalJSON marshal JSONTime to a JSON field
func (t *JSONTime) MarshalJSON() ([]byte, error) {
formatted := fmt.Sprintf("\"%s\"", t.Time.Format(timeFormat))
return []byte(formatted), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment