问题确实很简单,但不知道为什么事情不能以简单的方式工作。
我想要特定时区的日期时间。我的服务器的时区是美国/芝加哥
,但我想获取不同时区的当前日期时间。
- 我不想
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)
不起作用。预期/所需的输出应回显这些特定时区的当前时间。
如果我遗漏了什么,请提出建议。
最佳答案
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
关于php - 获取特定时区的 PHP 中的当前日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29452047/