2012-12-18 176 views
3

在下面的代码中,我需要为2个国家/地区的时区获取unixtimestamp。代码的输出会给我一个不同的日期,但时间戳并不相同。它仍然是一样的。任何人都可以提供一个解决方案来获得不同时区的不同时间戳吗?提前致谢。php中不同时区的时间戳

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 
+0

时间戳是连续的,它与时区无关,在地球上的每个地方都是一样的。 – zerkms

+1

“任何人都可以提供解决方案,为不同的时区获取不同的时间戳吗?” ---这是一个错误的问题。你的**原始**任务是什么? – zerkms

+0

我需要根据不同的时区使用php unixtimestamp和javascript(不使用任何ajax请求)来显示servertime。 – shyammtp

回答

3

您可以使用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 
+0

感谢我得到了我所需要的...... :-) – shyammtp

+0

[PHP时区](https://secure.php.net/manual/en/timezones.php) –

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 />'; 
+0

基本上这应该需要(PHP 5> = 5.2。 0)。感谢您的解决方案。 – shyammtp

+0

@shyammtp没问题我应该在我的回答中提到 – PhearOfRayne