英文:
How to set default Timezone on GORM time.Time data type
问题
我正在使用gorm和mysql作为数据库,使用go模块,如下所示:
- gorm.io/gorm v1.21.7
- github.com/go-sql-driver/mysql v1.6.0
我的系统时区是+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"`
}
在mysql表中,created_at和updated_at被声明为DATETIME类型,当我打印CreatedAt和UpdatedAt的值时,时区是+0000(UTC),当我尝试使用Time.In函数时,得到了错误的值,就好像我正在将时间从UTC转换为+07:00,我该如何告诉GORM我正在使用+07:00作为默认时区。
英文:
I am using gorm with mysql as database with go module like this :
- gorm.io/gorm v1.21.7
- github.com/go-sql-driver/mysql v1.6.0
My system timezone is +07:00 (Asia/Jakarta), and the mysql timezone is using the system timezone itself.
but something wrong happen when I've struct like this
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"`
}
on the mysql table created_at and updated_at declared as DATETIME, when I print the CreatedAt and UpdatedAt value, the timezone is +0000 (UTC), when I'm trying to use the Time.In function I got the wrong value, like I'm converting a time from UTC to +07:00, how can I declare to GORM that I'm using +07:00 as default timezone.
答案1
得分: 5
连接到MySQL
数据库时,请根据文档确保使用parseTime
和loc
参数:
> 将MySQL的DATE和DATETIME值扫描到time.Time变量中,这在Go中是DATE和DATETIME在MySQL中的逻辑等效。您可以通过将内部输出类型从[]byte更改为time.Time,并使用DSN参数parseTime=true来实现。您可以使用loc DSN参数设置默认的time.Time位置。
生成DSN连接字符串以设置parseTime
和loc
,请参见此处:
loc, _ := time.LoadLocation("Asia/Jakarta") // 处理任何错误!
c := mysql.Config{
User: "....",
Passwd: "....",
DBName: "....",
Addr: "....:3306",
Net: "tcp",
ParseTime: true,
Loc: loc,
}
fmt.Println(c.FormatDSN())
https://go.dev/play/p/5yoEbmrPqlZ
英文:
When connecting to the MySQL
database, ensure you leverage the parseTime
and loc
parameters as per the docs:
> 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.
to generate a DSN connection strings to set parseTime
& loc
see i.e.
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论