您可以定义
time支持两种格式的自己的字段类型:
type MyTime struct { time.Time}func (self *MyTime) UnmarshalJSON(b []byte) (err error) { s := string(b) // Get rid of the quotes "" around the value. // A second option would be to include them // in the date format string instead, like so below: // time.Parse(`"`+time.RFC3339Nano+`"`, s) s = s[1:len(s)-1] t, err := time.Parse(time.RFC3339Nano, s) if err != nil { t, err = time.Parse("2006-01-02T15:04:05.999999999Z0700", s) } self.Time = t return}type Test struct { Time MyTime `json:"time"`}[Try on Go Playground](https://play.golang.org/p/nYESNHgJI8)
在上面的示例中,我们采用预定义的格式
time.RFC3339Nano,其定义如下:
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
并删除
:
"2006-01-02T15:04:05.999999999Z0700"
time.Parse此处使用的这种时间格式在此处进行了描述:https : //golang.org/pkg/time/#pkg-
constants
另请参阅https://golang.org/pkg/time/#Parse的文档
time.Parse
PS
2006在时间格式字符串中使用年份的事实可能是因为Golang的第一版于该年发布。



