go json time format

2020-10-14  本文已影响0人  allenhaozi

参考: https://github.com/golang/go/issues/21990

import "time"

type Time time.Time

const (
    timeFormat = "2006-01-02 15:04:05"
)

func (t *Time) UnmarshalJSON(data []byte) (err error) {
    now, err := time.ParseInLocation(`"`+timeFormat+`"`, string(data), time.Local)
    *t = Time(now)
    return
}

func (t Time) MarshalJSON() ([]byte, error) {
    b := make([]byte, 0, len(timeFormat)+2)
    b = append(b, '"')
    b = time.Time(t).AppendFormat(b, timeFormat)
    b = append(b, '"')
    return b, nil
}

func (t Time) String() string {
    return time.Time(t).Format(timeFormat)
}
上一篇 下一篇

猜你喜欢

热点阅读