4

我有一个设置为本地时区的 MySQL 数据库。尽管数据库使用不同的时区,但时间被插入为 UTC 时间。我想在 MySQL 服务器上将时区更改为 UTC。我找到了有关如何执行此操作的文档,但我不情愿,因为我不知道这是否也会更改已存储在数据库中的值。

我的问题:更改 MySQL 服务器的时区是否也会更改已存储的值?

4

2 回答 2

8

In principle it shouldn't. There are various reasons why it shouldn't change, depending on the type of your values : mostly DATETIME and TIMESTAMP.

DATETIME values are never converted, so they are independent of the time zone.

TIMESTAMP values are converted (direct quote from the manual here --- I assume you have a fairly recent version of MySQL) "from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.) By default, the current time zone for each connection is the server's time. The time zone can be set on a per-connection basis. As long as the time zone setting remains constant, you get back the same value you store. If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored. This occurs because the same time zone was not used for conversion in both directions." (from http://dev.mysql.com/doc/refman/5.5/en/datetime.html).

So in both cases the data actually stored on the server does not change (which is as it should be), but the values that your queries will show may be different before and after.

于 2013-03-11T12:50:35.090 回答
3

这取决于您是否使用TIMESTAMPDATETIME列来存储您的时间戳。

TIMESTAMP当它们存储在 MySQL 的表中时,时间会自动从本地时间(准确地说:从连接的时区设置)转换为 UTC 时间。检索它们时,它们会从 UTC 转换为本地时间。

但是DATETIME时间戳的存储和检索与您的应用程序将它们呈现给 MySQL 完全一样。因此,如果您将默认时区更改为 UTC,然后检索您的TIMESTAMP值,您将恢复为 UTC。所以他们看起来像他们改变了。但改变的是自动翻译。

更改 MySQL 默认时区不会更改任何表内容。

您可以通过在连接到 MySQL 时发出以下命令来进行试验。

 SET  time_zone = '+0:00';

这将更改您的连接的时区设置,而不会更改任何其他内容。

重新配置您知道自己在做什么的生产服务器时要小心:您说您的“MySQL 数据库......设置为本地时区”。在更改任何内容之前,您需要准确调查它是如何设置的。因为这里是可以影响事物的设置。

(1) 运行 MySQL 服务器软件的服务器机器上的时钟设置。

(2) 那台机器上的时区设置。

(3) 正在运行的 MySQL 服务器中的默认(又名全局)时区设置。

在大多数现代服务器中,时钟设置为正确的 UTC 时间,时区设置设置为用户期望的任何本地时区。并且,您的 MySQL 服务器的默认时区设置设置为相同的本地时区。您需要验证这些事情是否正确。

如果您的服务器一天中的时间从标准时间自动正确地翻转到夏令时(美国的昨天早上),那么前两个时间可能是正确的。

如果你发出这个 MySQL 命令:SELECT @@global.time_zone' and get back either your local time zone name orSYSTEM the third is right. Also issueSELECT NOW()` 来仔细检查。如果你得到正确的时间,你的系统可能没问题。最后,发出这两个命令:

 SET  time_zone = '+0:00';
 SELECT NOW(); 

如果您从系统中获得当前正确的 UTC 时间,那么一切都是已知且良好的状态,您已准备好进行时区切换。

通过更改system_time_zoneMySQL 配置文件中的变量并重新启动 MySQL 服务器来进行切换。请参阅此处了解路线:

http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html

于 2013-03-11T13:14:49.640 回答