将当前时间戳(current_timestamp())插入到MariaDB表中的异常

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

Anomaly inserting current_timestamp() into MariaDB table

问题

你好!根据你的描述,你在使用Golang编写程序,将信息存储在MariaDB数据库中。你经常需要将一个created_at字段插入为current_timestamp(),这是非常常见的操作。

你的系统时间是UTC +1.00(BST),你使用的是Windows 10(21H1)操作系统。MariaDB设置为使用系统时间,在命令行中使用SELECT NOW()和SELECT CURRENT_TIMESTAMP()命令输出的结果也是系统时间。

然而,当你从程序中使用time.Now()函数将时间插入到MariaDB表中时,它被插入为UTC时间。可能存在一个简单的原因,但我不知道具体原因。你可以尝试以下方法来进行更改:

  1. 在程序中使用time.LoadLocation函数加载你所需的时区。例如,如果你想使用UTC +1.00时区,可以使用time.LoadLocation("Europe/London")

  2. 在插入数据之前,使用time.Now().In函数将时间转换为你所需的时区。例如,使用time.Now().In(yourTimeZone)将时间转换为你加载的时区。

  3. 确保你的MariaDB数据库的时区设置正确。你可以使用以下命令检查和更改时区设置:

    • 检查当前时区设置:SELECT @@global.time_zone, @@session.time_zone;
    • 更改全局时区设置:SET GLOBAL time_zone = 'your_time_zone';
    • 更改会话时区设置:SET time_zone = 'your_time_zone';

    请将"your_time_zone"替换为你所需的时区,例如'Europe/London'。

希望这些方法能帮助到你!如果你还有其他问题,请随时提问。

英文:

I'm writing a program using Golang (1.17.8), storing information in a MariaDB (10.6.5) database. I often need to store a created_at field inserted as current_timestamp() which is pretty common.
My system time is UTC +1.00 (BST) and I'm working with Windows 10 (21H1)
MariaDB is set to use system time and from the command line both SELECT NOW() and SELECT CURRENT_TIMESTAMP() output exactly that.
Logging the output of the Golang function time.Now() also gives system time.
If I insert time.Now() from my program into my MariaDB table it is inserted as UTC
Perhaps a simple reason exists for this but I do not know why. I have not ever used a different timezone and as mentioned, MariaDB reports it is using system time anyhow.
How can I change this please ?

答案1

得分: 1

根据文档所述,在没有时区的情况下,这是正常行为。您希望在输出中使用哪个时区?

你的服务器是否处于UTC时区?

英文:

As the documentation states, this is normal behavior in the absence of a timezone. Which time zone would you wish to use in your output?

Is your server in the UTC timezone by any chance?

huangapple
  • 本文由 发表于 2022年5月7日 22:59:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/72153682.html
匿名

发表评论

匿名网友

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

确定