我正在使用带有 mysql 的 gorm 作为带有 go 模块的数据库:
- gorm.io/gorm v1.21.7
- github.com/go-sql-driver/mysql v1.6.0
我的系统时区是+07:00(亚洲/ Jakarta ),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"`
}
在声明为 DATETIME 的 mysql 表 created_at 和 updated_at 上,当我打印 CreatedAt 和 UpdatedAt 值时,当我尝试使用 Time.In 时,时区为 +0000 (UTC)函数我得到了错误的值,就像我将时间从 UTC 转换为 +07:00,我如何向 GORM 声明我使用 +07:00 作为默认时区。
最佳答案
连接到 MySQL
数据库时,请确保根据 the docs 使用 parseTime
和 loc
参数:
to scan MySQL DATE and DATETIME values into time.Time variables, which is the logical equivalent in Go to DATE and DATETIME in MySQL. You can do that by changing the internal output type from []byte to time.Time with the DSN parameter parseTime=true. You can set the default time.Time location with the loc DSN parameter.
生成 DSN 连接字符串以设置 parseTime
& loc
see即
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())
关于mysql - 如何在 GORM time.Time 数据类型上设置默认时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71019353/