php - 获取特定时区的 PHP 中的当前日期时间

标签 php date datetime

问题确实很简单,但不知道为什么事情不能以简单的方式工作。

我想要特定时区的日期时间。我的服务器的时区是美国/芝加哥,但我想获取不同时区的当前日期时间。

  1. 我不想date_default_timezone_set,因为它会更改所有日期时间函数的时区。
  2. 我尝试使用不同的时区值 $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

Demo

关于php - 获取特定时区的 PHP 中的当前日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29452047/

相关文章:

php - MySQL 使用 ORDER BY 连接表会产生意想不到的结果

php - 如何从多维数组中删除一些重复元素

php - OpenEMR 5.0.0 布局中缺少保险选项

php - 当我将其设置为不显示时,数据库仍然显示较旧的条目

python - 如何减去 Pandas Dataframe 中的两个日期时间值

c++ - 用日期时间命名输出文件

php - 在 PHP 中解析时需要在 JSON feed 中保留反斜杠

PHP日期偏移量

date - Kettle数据整合: dates always blank on excel output or excel writer

javascript - 月/日/年月日 HH :MM:SS AM/PM date validation regular expression in javascript