簡體   English   中英

php中不同時區的時間戳

[英]Timestamp for different timezones in php

在下面的代碼中,我需要獲得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

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

這應該工作,我改變了你原來的方式使用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 />';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM