修改gmdate PHP函数的时区


Change time zone of gmdate PHP function

我正在使用gmdate PHP函数将当前日期插入数据库,但它显示GMT时间,我可以将其更改为我的时区+3吗?

这是代码

$sql = "INSERT INTO Students
VALUES ('','" . $info[$i]['firstname'] . "', '" . $info[$i]['lastname'] . "', 
        '" . $info[$i]['sex'] . "', '" . $info[$i]['major'] . "', 
        '" . $info[$i]['favorite'] . "', '" . $info[$i]['GPA'] . "',
        '". gmdate('m/d/Y g:i:s A') . "')" ;

"+3"不是"时区"。它是UTC/GMT的偏移量,根据DST设置,该偏移量在一年中可能会发生变化。时区类似于"欧洲/柏林"或"亚洲/东京"。

一旦你决定了一个真正的时区:

date_default_timezone_set('Europe/Berlin');
echo date('m/d/Y g:i:s A');

$date = new DateTime('now', new DateTimeZone('Europe/Berlin'));
echo $date->format('m/d/Y g:i:s A');

如果你只需要使用"+3",那么a)你就完蛋了,b)你可以简单地在任何时间戳后面加上"3小时":

date_default_timezone_set('UTC');
echo date('m/d/Y g:i:s A', strtotime("$offset hours"));
echo date('m/d/Y g:i:s A', time() + ($offset * 60 * 60));
$date = new DateTime;
$date->modify("$offset hours");
echo $date->format('m/d/Y g:i:s A');

不,您应该使用date()。或者使用DateTime对象对时区进行更多的控制。

我强烈建议存储GMT日期和时间,并在显示数据时计算回您自己的时区。

$datetime = new DateTime('now');
$dateTime->setTimeZone(new DateTimeZone('Europe/London')); // Change to london time.
echo $dateTime->format('m/d/Y g:i:s A');

您应该始终使用时区名称,而不是偏移量。你说的是+3的偏移量,但我确定你一年只有6个月生活在UTC+3:00。

以下是我的建议:

您可以使用时区偏移量(date("Z"))来处理服务器上的时区

   $timestamp = time()+date("Z");
echo gmdate("Y/m/d H:i:s",$timestamp);