在GORM中,如何配置特定时区的autoCreateTime和autoUpdateTime?

huangapple go评论89阅读模式
英文:

In GORM, how to configure autoCreateTime and autoUpdateTime in specific timezone?

问题

我的MariaDB数据库中的created_at和updated_at字段之前填充了我特定时区(Europe/Paris)的日期。

我现在已经集成了GORM(v1.23.8),但是在我的GORM模型中使用autoCreateTime和autoUpdateTime时,日期总是以UTC格式写入。我该如何配置GORM,使得autoCreateTime和autoUpdateTime的日期以不同于UTC的时区写入。

我尝试在MariaDB连接字符串中添加Loc和ParseTime参数,但这并没有解决问题。

英文:

The created_at and updated_at fields of my MariaDB database are previously filled with dates of my specific timezone (Europe/Paris).

I have now integrated GORM (v1.23.8), however, when using autoCreateTime and autoUpdateTime in my GORM model, the dates are always written in UTC. How can I configure GORM, so that the autoCreateTime and autoUpdateTime dates are written in a different timezone than UTC.

I have tried to add the Loc and ParseTime params to the MariaDB connection string, but that didn't fix the issue.

答案1

得分: 1

GORM v1.23.8规定了autoCreateTime和autoUpdateTime字段配置应包含UNIX时间戳,它隐式地使用UTC时区,因此似乎无法更改autoCreateTime和autoUpdateTime的时区。

解决方法是不使用autoCreateTime和autoUpdateTime来指定created_at和updated_at字段,而是将它们作为普通日期字段,并在代码中手动设置日期。

英文:

GORM v1.23.8 specifies the autoCreateTime and autoUpdateTime field config to contain a UNIX timestamp, which is implicitly UTC timezone, therefor it seems impossible to change the timezone for autoCreateTime and autoUpdateTime.

The workaround would be to not specify your created_at and updated_at fields with autoCreateTime and autoUpdateTime, but as normal date fields and set the dates manually in your code.

答案2

得分: 0

尽管有许多原因可以将日期存储在数据库中作为UTC时间(例如,许多前端框架期望日期为UTC,并且会自行进行本地化),但由于我正在处理一个已将数据库日期存储为本地时区的遗留系统,以下是我找到的适用于我的解决方案:

gormDB, err := gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", userName, password, hostName, port, dbname)), &gorm.Config{
	NowFunc: func() time.Time {
		currentTime := time.Now()
		_, offset := currentTime.Zone()
		mysqlTime := currentTime.Add(time.Second * time.Duration(offset))
		return mysqlTime
	},
})

这段代码将数据库的日期转换为本地时间。

英文:

While there are many reasons why you should store your dates in your database as UTC (e.g. many frontend frameworks expect dates in UTC, and will localize them themselves), since I'm working on a legacy system which already stored the database dates in the local time zone, here is a solution that I found works for me:

gormDB, err := gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", userName, password, hostName, port, dbname)), &gorm.Config{
	NowFunc: func() time.Time {

		currentTime := time.Now()
		_, offset := currentTime.Zone()
		mysqlTime := currentTime.Add(time.Second * time.Duration(offset))
		return mysqlTime
	},
})

huangapple
  • 本文由 发表于 2022年8月26日 15:17:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/73497397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定