mik*_*ika 7 php timezone datetime unix-timestamp
从DateTime对象,我有兴趣在不同的TimeZones中获取时间.正如DateTime :: setTimezone doc中所解释的,当从字符串创建DateTime对象时,这非常有效:
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('UTC'));
echo $date->format('Y-m-d H:i:sP') . "\n";
echo $date->getTimestamp() . "\n";
Run Code Online (Sandbox Code Playgroud)
上述实施例将输出:
2000-01-01 00:00:00 + 12:00
2000-01-01 01:45:00 + 13:45
1999-12-31 12:00:00 + 00:00
946641600
现在是有趣的部分:如果我们选择时间戳,并按照手动说明启动我们的DateTime对象.
$date2 = new DateTime('@946641600');
$date2->setTimezone(new DateTimeZone('Pacific/Nauru'));
echo $date2->format('Y-m-d H:i:sP') . "\n";
$date2->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date2->format('Y-m-d H:i:sP') . "\n";
$date2->setTimezone(new DateTimeZone('UTC'));
echo $date2->format('Y-m-d H:i:sP') . "\n";
echo $date2->getTimestamp() . "\n";
Run Code Online (Sandbox Code Playgroud)
在这里我们得到:// [编辑] humm ...对不起,这个输出是错误的...
1999-12-31 12:00:00 + 00:00 1999-12-31 12:00:00
+ 00: 00
1999-12-31
12:00:00 + 00:00 946641600
UTC永远!我们不能再改变时区了!?!
是PHP还是我?版本5.3.15
好的,所以我自己也生气了.当然,我是一个错误的人...
为了做到这一点,我只需要在这里和这里获取文档中相关的位.
手册说:
// Using a UNIX timestamp. Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";
Run Code Online (Sandbox Code Playgroud)
实际上,您可以使用setTimezone在您的时区中再次获取时间(如果您的系统设置方式可以预期!):
$timezone = new DateTimeZone('Europe/Madrid');
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
Run Code Online (Sandbox Code Playgroud)
注意
$date = new DateTime('@1306123200', new DateTimeZone('Europe/Madrid'));
Run Code Online (Sandbox Code Playgroud)
是误导,因为你仍然会在UTC!(是的,它在构造函数的doc中非常清楚地指定.所以要小心;)
谢谢@hakre全部谢谢!