美文网首页
go json time format

go json time format

作者: allenhaozi | 来源:发表于2020-10-14 20:37 被阅读0次

参考: 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)
}

相关文章

网友评论

      本文标题:go json time format

      本文链接:https://www.haomeiwen.com/subject/pbxgpktx.html