gorm 扫描日期获取结果为零值

2021-04-04 20:58:23 +08:00
 marcosteam

程序代码如下:

type CheckInStatus struct {
	ExpTime time.Time
	LastCheckTime time.Time
	TransferEnable int64
}
...
database.Db.
	Debug().
	Table("users").
	Select("expire_time,last_check_in_time,transfer_enable").
	Where("id = ?",uid).
	Scan(&checkInStatus)

扫描出来的结果是

2021/04/04 20:52:49 0001-01-01 00:00:00 +0000 UTC
2021/04/04 20:52:49 0001-01-01 00:00:00 +0000 UTC
2021/04/04 20:52:49 257949696

gorm 成功获取到了数据,但是没有将日期解析为正确的值... 已经在数据库连接 URL 中设置了 &parseTime=True&loc=Local

1528 次点击
所在节点    Go 编程语言
3 条回复
mogg
2021-04-04 21:53:37 +08:00
名字对不上,要么在结构体里声明列名,比如 ExpTime time.Time `gorm:"column:expire_time"`,要么 select 的时候用一下 as,Select("expire_time as exp_time ……
toomlo
2021-04-05 17:45:18 +08:00
```golang
type TimeN struct {
time.Time
}

type (t TimeN) String() string{
return t.Format(`2006-01-02 15:04:05`)
}

type CheckInStatus struct {
ExpTime TimeN
LastCheckTime TimeN
TransferEnable int64
}
```

如果你需要将 CheckInStatus 这个结构的实例 json 格式化的话 还需要重写 Time 的 MarshalJSON 和 UnmarshalJSON 方法
marcosteam
2021-04-06 10:17:18 +08:00
@mogg 已经解决,感谢!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/767995

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX