问题很简单,但不知道为什么事情不能以简单的方式运作。
我想拥有特定时区的日期时间。我的服务器的时区是America/Chicago
,但我希望得到不同时区的当前日期时间。
date_default_timezone_set
,因为它会更改所有日期时间函数的时区。$now = new DateTime(null, new DateTimeZone('Europe/Stockholm'));
使用不同的时区值,但都返回相同的值。考虑以下代码
$current_time = date('Y-m-d H:i:s');
echo "The current server time is: " . $current_time . "\r\n";
$now = new DateTime(null, new DateTimeZone('America/New_York'));
echo "America/New_York = ". $now->getTimestamp() . "\r\n";
$now = new DateTime(null, new DateTimeZone('Europe/Stockholm'));
echo "Europe/Stockholm = ". $now->getTimestamp() . "\r\n";
$now = new DateTime(null, new DateTimeZone('Asia/Muscat'));
echo "Asia/Muscat = ".$now->getTimestamp() . "\r\n";
$current_time = date('Y-m-d H:i:s');
echo "The current server time is: " . $current_time . "\r\n";
以上代码导致以下输出
The current server time is: 2015-04-04 17:06:01
America/New_York = 1428185161
Europe/Stockholm = 1428185161
Asia/Muscat = 1428185161
The current server time is: 2015-04-04 17:06:01
并且所有三个值都相同,意味着new DateTimeZone(XYZ)
不起作用。预期/需要的输出应该回显那些特定时区的当前时间。
如果我遗漏任何东西,请提供建议。
答案 0 :(得分:4)
Unix时间戳始终为UTC,因此始终相同。尝试使用c
格式化程序查看差异:
$current_time = date('Y-m-d H:i:s');
echo "The current server time is: " . $current_time . "\r\n";
$now = new DateTime(null, new DateTimeZone('America/New_York'));
echo "America/New_York = ". $now->format('c') . "\r\n";
$now = new DateTime(null, new DateTimeZone('Europe/Stockholm'));
echo "Europe/Stockholm = ". $now->format('c') . "\r\n";
$now = new DateTime(null, new DateTimeZone('Asia/Muscat'));
echo "Asia/Muscat = ".$now->format('c') . "\r\n";
$current_time = date('Y-m-d H:i:s');
echo "The current server time is: " . $current_time . "\r\n";
The current server time is: 2015-04-04 22:26:56
America/New_York = 2015-04-04T18:26:56-04:00
Europe/Stockholm = 2015-04-05T00:26:56+02:00
Asia/Muscat = 2015-04-05T02:26:56+04:00
The current server time is: 2015-04-04 22:26:56