MySQL与PHP的时区问题

时间:2016-11-30 18:40:55

标签: php mysql timezone

背景:我有一些PHP代码,可以根据各种规则计算下次重复发送消息的时间。我还有一个完整页面,可以仔细检查下一次重现是否正确。由于时区问题,我不确定如何解决,理智页面显示一些问题,我不确定它们是否确实存在问题。

我相信这些都出现了,因为(未来)日期是在BST(英国夏令时)期间,但欧洲/伦敦时区目前是格林威治标准时间。

我创建了一个非常简化的测试页面来调试和测试一个例子。代码如下:

// Not included: DB connection setup, which includes a query to set the MySQL session timezone to the current timezone for Europe/London as calculated by PHP

// Copied from a comment at http://php.net/manual/en/function.date-default-timezone-get.php
function timezone_offset_string( $offset )
{
    return sprintf( "%s%02d:%02d", ( $offset >= 0 ) ? '+' : '-', abs( $offset / 3600 ), abs( $offset % 3600 ) );
}

$offset = timezone_offset_get( new DateTimeZone( date_default_timezone_get() ), new DateTime() );

// query_multiple() is a function to get a single result from the database and return it as the specified PDO type
$db = query_multiple("SELECT NextRecurrence, UNIX_TIMESTAMP(NextRecurrence) AS NextTS, IF(@@session.time_zone = 'SYSTEM', @@system_time_zone, @@session.time_zone) AS DBTZ FROM RecurringMessages WHERE RecurID=96 LIMIT 1", "", "", PDO::FETCH_ASSOC);

print "DB Date of NextRecurrence  : ".$db['NextRecurrence']."<br>";
print "DB timestamp of NextRecurrence  : ".$db['NextTS']."<br>";
print "DB timezone  : ".$db['DBTZ']."<br>";

print "PHP timezone and offset: " .date_default_timezone_get().", ".timezone_offset_string( $offset ) . "<br>";
print "PHP date of NextTS : ".date('Y-m-d H:i:s', $db['NextTS'])."<br>";

此页面的输出如下:

DB Date of NextRecurrence : 2017-05-24 10:00:00
DB timestamp of NextRecurrence : 1495620000
DB timezone : +00:00
PHP timezone and offset: Europe/London, +00:00
PHP date of NextTS : 2017-05-24 11:00:00

正如您所看到的,即使PHP和MySQL时区相同,PHP日期也会相差一小时。如上所述,我认为这是因为所提供的日期是在BST期间,而欧洲/伦敦目前是GMT。

如果我将1495620000放入http://www.epochconverter.com/,它会告诉我它是2017年5月24日星期三10:00:00 GMT

我目前不确定有两件事

  1. 当前数据库条目是否正确?说到2017年5月24日,这条消息会在10:00或11:00发送吗?用于发送消息的PHP代码在连接后立即为MySQL设置会话时区,以匹配Europe / London的当前时区。
  2. 如果数据库条目正确,如何获取PHP日期函数以便为将来的日期提供正确的输出?如果PHP日期函数是正确的,我如何(通常)使用正确的日期更新MySQL记录?我所知道的是它应该在2017年5月24日10:00发送。目前,查询会使用UPDATE SET NextRecurrence='2017-05-24 10:00:00' ...
  3. 进行更新

1 个答案:

答案 0 :(得分:0)

我想通了(我想)。

因为MySQL目前处于GMT状态,所以我需要在GMT中向Y-m-d H:i:s格式化日期和时间,即使日期是在BST期间。

// $ts contains the correct unix timestamp

$offsetnow=date('Z');
$tsoffset=date('Z', $ts);
$diff=$offsetnow-$tsoffset;

// Add the difference to the timestamp so that the PHP date returns the appropriately presented Y-m-d H:i:s to MySQL, which as of writing this is GMT.
$ts+=$diff;

$query="UPDATE Recurrences SET NextRecurrence='".date('Y-m-d H:i:s', $ts)."' ...

如果有人在我正在做的事情上看到错误,请告诉我!