Riz*_*ima 4 mysql datetime go go-gorm
我使用 gorm 和 mysql 作为带有 go 模块的数据库,如下所示:
我的系统时区是+07:00(亚洲/雅加达),并且mysql时区正在使用系统时区本身。
但是当我这样构造时会发生错误
type Name struct {
ID uint64 `gorm:"id;primaryKey;autoIncrement"`
Name string `gorm:"column:name"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
Run Code Online (Sandbox Code Playgroud)
在声明为DATETIME的mysql表created_at和updated_at上,当我打印CreatedAt和UpdatedAt值时,时区是+0000(UTC),当我尝试使用Time.In函数时,我得到了错误的值,就像我'我正在将时间从 UTC 转换为 +07:00,我如何向 GORM 声明我使用 +07:00 作为默认时区。
连接到数据库时,请确保按照文档MySQL利用parseTime和参数:loc
将 MySQL DATE 和 DATETIME 值扫描到 time.Time 变量中,这与 Go to DATE and DATETIME in MySQL 中的逻辑等效。您可以通过将内部输出类型从 []byte 更改为 time.Time 并使用 DSN 参数 parseTime=true 来实现此目的。您可以使用 loc DSN 参数设置默认时间.时间位置。
生成一个 DSN 连接字符串来设置parseTime和loc 查看ie
loc, _ := time.LoadLocation("Asia/Jakarta") // handle any errors!
c := mysql.Config{
User: "....",
Passwd: "....",
DBName: "....",
Addr: "....:3306",
Net: "tcp",
ParseTime: true,
Loc: loc,
}
fmt.Println(c.FormatDSN())
Run Code Online (Sandbox Code Playgroud)
https://go.dev/play/p/5yoEbmrPqlZ
| 归档时间: |
|
| 查看次数: |
11422 次 |
| 最近记录: |