0

假设我在多个位置有多个服务器,并且我想将 MySQL 的 datetime 类型用于字段日期,并且我总是希望字段日期具有 UTC 时间戳,因此UTC_TIMESTAMP()当我将其添加到数据库时我会执行 a 。现在说我想让 MySQL 为它输出 UNIX TIMESTAMP。

当我在服务器 AI 上执行此操作时,得到字符串“2009-06-17 12:00:00”,在它上面执行 UNIX_TIMESTAMP(STRING) 会给我返回数字 1245240000。UTC 时间为 2009-06-17 12:00:00。现在我在服务器 B 上做同样的事情。我得到了相同的字符串,因为它是 UTC 字符串,但是当再次执行 UNIX_TIMESTAMP(STRING) 时,我得到了错误的数字 1245232800,这是 UTC +2 时间。我该如何解决这个问题?我应该在 PHP 端进行从字符串到时间戳的转换吗?

4

2 回答 2

1

G'day,

I'll ask the obvious here, did you check the date and time on both machines?

Edit: ... and the MySQL timezone was the same on both machines?

Update: Ok. The problem is in the fact that the timestamp string being passed into UNIX_TIMESTAMP is interpreted to be a value in the current timezone which is then converted back to UTC so, because you're in MEZ, two hours is subtracted to return it back to UTC so 7200 is subtracted from your timestamp when it is converted back to a Unix timestring.

Hence, the variation you see when using UNIX_TIMESTAMP() to convert is back to a Unix Epoch timestring.

BTW Shouldn't you be using a TIMESTAMP type for storing off your UTC_TIMESTAMPs instead of DATETIME type?

Update: Decoupling presentation time from stored time is definitely the way to go. You can then reuse the same data all around the world and only have to convert to and from local time when you are presenting the data to a user.

If you don't do this then you are going to have to store off the timezone when the timestamp was made and then go into all sorts of complicated permutations of having to work out if

  • the local timezone was in daylight saving time when it was stored,
  • what the difference is between the timezone at the time that the data was stored and the timezone where the data is to be presented.

Leaving it all storeed as UTC gets rid of that.

Most users won't be that happy if they have to work out the local time themselves based on the UTC time returned so systems usually convert to current local time for the user.

This is of course if the user wants the data expressed in local time which is usually the case. The only widely used system I can think of, off the top of my head, that stores and presents its data in UTC is system for air traffic control and flight plan management which are always kept in UTC (or ZULU time to be more precise).

HTH

cheers,

于 2009-06-19T13:31:27.700 回答
0

你试过这样做吗?

一起执行此指令。

SET time_zone = 'UTC';
SELECT FROM_UNIXTIME(0), UNIX_TIMESTAMP('2009-06-17 12:00:00'); 
// 1970-01-01 00:00:00        1245240000

它们只影响客户端会话,而不影响服务器配置。

于 2009-06-19T14:29:34.447 回答