mysql - 如何在 GORM time.Time 数据类型上设置默认时区

标签 mysql datetime go go-gorm

我正在使用带有 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 使用 parseTimeloc 参数:

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())

https://go.dev/play/p/5yoEbmrPqlZ

关于mysql - 如何在 GORM time.Time 数据类型上设置默认时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71019353/

相关文章:

java - 失败: alter table comment drop foreign key

mysql - 如何在一个查询中过滤重复项和分组依据?

c# - 如何使用 CultureInfo 获取 12 小时或 24 小时时间(不带日期)

javascript - moment.js 和 moment.php 是一样的吗?

amazon-web-services - 使用 gosdk 在 Dynamodb 中执行 UpdateItem 时如何将 ValueBuilder 对象声明为 StringSet?

go - 如何将字符串作为参数传递给 Golang 指针接收函数?

mysql - 错误代码 : 1690 DOUBLE value is out of range in pow((75 + 1), 261)

c# - 连接到 PHPMyAdmin 托管数据库

javascript - 使用 moment.js 转换日期/时间格式

go - 在 golang 中扩展包结构