Golang将time.Now插入数据库时会被转换为UTC时间。

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

Golang inserting time.Now into database being shifted to UTC

问题

我正在尝试将time.Now()字段插入数据库,但问题是时间会被转换为UTC。我知道这样做的想法是始终这样处理,然后在向用户展示时转换为本地时间。问题是我继承了这个系统,它目前已经非常深入,不容易改变。

有什么建议吗?我看到可以在DSN中设置loc,但没有解释要更改为什么,也没有解释其实际效果,所以我希望能得到相关信息。

编辑:一些信息,这是一个使用go-mysql 1.1和go 1.6.3的MySQL数据库。数据被插入到一个DATETIME字段中。

数据在插入时是不正确的。GORM Debug显示的时间和MySQL查询日志显示的时间是不一致的。

我发现问题是go-mysql驱动程序会自动将时间转换为UTC,可以通过在DSN中使用loc参数来更改。然而,这也会改变时间的返回方式。

要解决这个问题,请在DSN中添加loc=Local。

英文:

I am trying to insert a time.Now() field into the database, but what keeps happening is the time is shifted forward to UTC. I understand the idea is to always to that then convert to local time when presenting to the user. Problem is I have inherited this system and it is currently far to ingrained to be easily changed.

Any tips? I saw that you can set the loc in the DSN but it does not explain what to change it to nor its actual effect, so I would appreciate information there.

Edit: Some information, it is MySQL DB,using go-mysql 1.1 and go 1.6.3. The data is being inserted into a DATETIME field.

The data is incorrect at the insert. GORM Debug shows one time and MySQL query logger shows it shifted forward.

I have found that the issue is that the go-mysql driver automatically shifts times to be UTC, and this can be altered using the loc parameter in the DSN. This however also changes how the time is returned.

To resolve this add loc=Local to your DSN.

答案1

得分: 6

这是我一直使用的方法来存储本地时间,即使你的VPS位于另一个时区的国家也可以正常工作:

db, err = gorm.Open("mysql", "root:@tcp(localhost:3306)/mydatabase?charset=utf8&parseTime=True&loc=America%2FSao_Paulo")
英文:

This is the way I use to always store local time. Works fine even if your VPS is located on another timezone country:

db, err = gorm.Open("mysql", "root:@tcp(localhost:3306)/mydatabase?charset=utf8&parseTime=True&loc=America%2FSao_Paulo")

答案2

得分: -3

因为在 Golang 中解析时间时会使用 UTC。

英文:

because time in golang parse will use the UTC

huangapple
  • 本文由 发表于 2016年7月20日 03:11:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/38466686.html
匿名

发表评论

匿名网友

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

确定