go 结构体通过json转Map,中*time.Time的问题

41 阅读2分钟

go gorm mysql Incorrect datetime value: '2023-10-08T00:00:00z' for column 'expire-time' at row 1

在使用gorm更新数据的时候发现,同样是使用*time.Time 类型,为什么更新就会出现上面的问题

在查了好久上面错误信息发现,原来是数据库中设置的类型为datatime,而插入的数据不是这个类型导致的报错

这个时候就疑惑了,同样都是*time.Time类型为啥create可以,update就报错呢,找了好久突然想到,会不会是哪里对数据进行处理了

果不其然,有一个地方把结构体转为了map,而且是使用json进行转换的,导致了时间格式出现错误。

下面是示例代码:

type TestTime struct {
   CreateAt *time.Time `json:"create_at"`
}

func StructToMap() {
   t := time.Now()
   model := TestTime{CreateAt: &t}
   raw := make(map[string]interface{})
   fmt.Println("TestTime ::", model)

   j, _ := json.Marshal(model)

   fmt.Println("json::", j)
   err := json.Unmarshal(j, &raw)
   fmt.Println("json Unmarshal error ::", err)

   fmt.Println("json Unmarshal::", raw)
}

以上输出内容:

 TestTime :: {2024-01-03 17:55:48.2288373 +0800 CST m=+0.019907701}
 json:: [123 34 99 114 101 97 116 101 95 97 116 34 58 34 50 48 50 52 45 48 49 45 48 51 84 49 55 58 53 53 58 52 56 46 50 50 56 56 51 55 51 43 48 56 58 48 48 34 125]
 json Unmarshal error :: <nil>
 json Unmarshal:: map[create_at:2024-01-03T17:55:48.2288373+08:00]

仔细比对:

*time.Time 输出为 2024-01-03 17:55:48.2288373 +0800 CST m=+0.019907701

map 输出为:2024-01-03T17:55:48.2288373+08:00

至此,发现问题

留有疑惑 json.Unmarshal 转换后,这个时间是什么类型的,为什么会导致不一样呢

还需要慢慢学习了,如果有大佬知道,请赐教~