1 回答

TA貢獻1942條經驗 獲得超3個贊
錯誤已經說明出了什么問題:
將時間“2019-01-01 00:00:00”解析為“2006-01-02T15:04:05Z07:00”:無法將“00:00:00”解析為“T”
您正在傳遞"2019-01-01 00:00:00"
,而它需要不同的時間格式,即RFC3339(UnmarshalJSON 的默認格式)。
要解決這個問題,您要么想要以預期的格式傳遞時間"2019-01-01T00:00:00Z00:00"
,要么像這樣定義您自己的類型CustomTime
:
const timeFormat = "2006-01-02 15:04:05"
type CustomTime time.Time
func (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
}
去游樂場的例子。
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報