V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
marcosteam

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

  •  
  •   marcosteam · Apr 4, 2021 · 2564 views
    This topic created in 1850 days ago, the information mentioned may be changed or developed.

    程序代码如下:

    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 replies    2021-04-06 10:17:18 +08:00
    mogg
        1
    mogg  
       Apr 4, 2021
    名字对不上,要么在结构体里声明列名,比如 ExpTime time.Time `gorm:"column:expire_time"`,要么 select 的时候用一下 as,Select("expire_time as exp_time ……
    toomlo
        2
    toomlo  
       Apr 5, 2021
    ```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
       Apr 6, 2021
    @mogg 已经解决,感谢!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5192 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 09:37 · PVG 17:37 · LAX 02:37 · JFK 05:37
    ♥ Do have faith in what you're doing.