V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
marcosteam
V2EX  ›  Go 编程语言

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

  •  
  •   marcosteam · 2021-04-04 20:58:23 +08:00 · 1497 次点击
    这是一个创建于 1088 天前的主题,其中的信息可能已经有所发展或是发生改变。

    程序代码如下:

    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

    3 条回复    2021-04-06 10:17:18 +08:00
    mogg
        1
    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
        2
    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
        3
    marcosteam  
    OP
       2021-04-06 10:17:18 +08:00
    @mogg 已经解决,感谢!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3157 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:31 · PVG 20:31 · LAX 05:31 · JFK 08:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.