该错误已说明出了什么问题:
将时间“” 2019-01-01 00:00:00“”解析为“” 2006-01-02T15:04:05Z07:00“”:无法将“
00:00:00”“解析为” T“
您正在传递,
"2019-01-0100:00:00"而它期望使用不同的时间格式,即RFC3339(UnmarshalJSON的默认值)。
为了解决这个问题,您要么希望以期望的格式传递时间,要么像这样
"2019-01-01T00:00:00Z00:00"定义自己的类型
CustomTime:
const timeFormat = "2006-01-02 15:04:05"type CustomTime time.Timefunc (ct *CustomTime) UnmarshalJSON(data []byte) error { newTime, err := time.Parse(timeFormat, strings.Trim(string(data), """)) if err != nil { return err } *ct = CustomTime(newTime) return nil}func (ct *CustomTime) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("%q", time.Time(*ct).Format(timeFormat))), nil}小心,您可能还需要实现
Valuer和
Scanner接口,以便在数据库中进行解析时,如下所示:
func (ct CustomTime) Value() (driver.Value, error) { return time.Time(ct), nil}func (ct *CustomTime) Scan(src interface{}) error { if val, ok := src.(time.Time); ok { *ct = CustomTime(val) } else { return errors.New("time Scanner passed a non-time object") } return nil}转到Playground示例。



