【问题标题】:Timestamp for different timezones in phpphp中不同时区的时间戳
【发布时间】:2012-12-05 06:37:10
【问题描述】:

在下面的代码中,我需要获取 2 个国家时区的 unixtimestamp。代码的输出会给我一个不同的日期,但时间戳彼此没有不同。它保持不变。谁能给出一个解决方案来为不同的时区获取不同的时间戳?提前致谢。

date_default_timezone_set('Asia/Calcutta');
echo date("Y-m-d H:i:s")."<br/>"; //2012-12-18 12:12:12
echo strtotime(date("Y-m-d H:i:s",time()))."<br/>"; //1355812934

date_default_timezone_set('Europe/London');
echo date("Y-m-d H:i:s")."<br/>"; //2012-12-18 06:12:12
echo strtotime(date("Y-m-d H:i:s",time()))."<br/>"; //1355812934

【问题讨论】:

  • 时间戳是连续的,它与时区无关,在地球上的每个地方都是一样的。
  • "谁能给出一个解决方案来为不同的时区获取不同的时间戳?" --- 这是一个错误的问题。你的最初任务是什么?
  • 我需要根据不同的时区使用 php unixtimestamp 和 javascript(不使用任何 ajax 请求)来显示服务器时间。
  • 为什么你需要任何Unix时间戳操作?不要混淆表示和数据。世界各地的时间都是一样的。

标签: php datetime time timezone unix-timestamp


【解决方案1】:

您可以使用date("Z") 以秒为单位获取时区偏移量。然后根据需要计算。

date_default_timezone_set('Asia/Calcutta');
echo 'Local time : '.date("r").'<br>'; // local time
echo 'Offset : '.date("Z").'<br>'; // time zone offset from UTC in seconds 
echo 'UTC Time : '.date('r', strtotime(date("r")) + (date("Z")*-1)); echo '<br><br>'; // this is UTC time converted from Local time

date_default_timezone_set('Europe/London');
echo 'Local time : '.date("r").'<br>'; // local time
echo 'Offset : '.date("Z").'<br>'; // time zone offset from UTC in seconds 
echo 'UTC time : '.date('r', strtotime(date("r")) + (date("Z")*-1)); echo '<br><br>'; // this is utc time converted from Local time

输出:

Local time : Tue, 18 Dec 2012 10:53:07 +0530
Offset : 19800
UTC Time : Tue, 18 Dec 2012 05:23:07 +0530

Local time : Tue, 18 Dec 2012 05:23:07 +0000
Offset : 0
UTC time : Tue, 18 Dec 2012 05:23:07 +0000  

【讨论】:

  • 谢谢我得到了我需要的东西...:-)
【解决方案2】:

这应该可行,我改变了你原来的方式来使用 php DataTimeZone 类。试试这个,应该很容易理解:

$dateTimeZoneCalcutta = new DateTimeZone("Asia/Calcutta");
$dateTimeCalcutta = new DateTime("now", $dateTimeZoneCalcutta);
$calcuttaOffset = $dateTimeZoneCalcutta->getOffset($dateTimeCalcutta);
$calcuttaDateTime = date("Y-m-d H:i:s", time() + $calcuttaOffset);

echo 'Local Server Time: ' . date("Y-m-d H:i:s", time()) . '<br />';
echo 'Calcutta Time: ' . $calcuttaDateTime . '<br />';
echo 'Calcutta Timestamp: ' . strtotime($calcuttaDateTime)  . '<br />';
echo '<br /><br />';

$dateTimeZoneLondon = new DateTimeZone("Europe/London");
$dateTimeLondon = new DateTime("now", $dateTimeZoneLondon);
$londonOffset = $dateTimeZoneLondon->getOffset($dateTimeLondon);
$londonDateTime = date("Y-m-d H:i:s", time() + $londonOffset);

echo 'Local Server Time: ' . date("Y-m-d H:i:s", time()) . '<br />';
echo 'London Time: ' . $londonDateTime . '<br />';
echo 'London Timestamp: ' . strtotime($londonDateTime) . '<br />';

【讨论】:

  • 基本上这应该需要(PHP 5 >= 5.2.0)。感谢您的解决方案。
  • @shyammtp 没问题,我应该在回答中提到这一点
猜你喜欢
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
  • 2023-03-07
  • 2014-11-07
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
相关资源
最近更新 更多