8

从 DateTime 对象中,我对获取不同时区的时间感兴趣。正如DateTime::setTimezone文档中所解释的,当从字符串创建 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";

以上示例将输出:
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";

在这里我们得到: // [edit] 嗯...对不起,这个输出是错误的...
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

4

2 回答 2

7

好吧,所以我自己生气了。当然,我是错的……为了直截了当,我将在此处此处
的文档中挑选相关的内容。 手册说:

// 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";

因此,确实,您可以使用 setTimezone 在您的时区中再次获取时间(如果您的系统是这样设置的,这是可以预期的!):

$timezone = new DateTimeZone('Europe/Madrid');
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));

注意

$date =  new DateTime('@1306123200', new DateTimeZone('Europe/Madrid'));

具有误导性,因为无论如何您都会在UTC!(是的,在构造函数的文档中非常清楚地指定了它。所以要小心;)

谢谢@hakre 谢谢大家!

于 2012-10-17T15:17:31.303 回答
4

这只是你。就 PHP 而言,一切都很好,花花公子,PHP 手册很好地涵盖了这一点:http ://www.php.net/manual/en/datetime.construct.php

于 2012-10-17T14:23:18.627 回答