[英]PHP timezone offset incorrect
以下PHP代碼:
function serverTimeZone_offset($userTimeZone)
{
$userDateTimeZone = new DateTimeZone($userTimeZone);
$userDateTime = new DateTime("now", $userDateTimeZone);
$serverTimeZone = date_default_timezone_get();
$serverDateTimeZone = new DateTimeZone($serverTimeZone);
$serverDateTime = new DateTime("now", $serverDateTimeZone);
return $serverDateTimeZone->getOffset($userDateTime);
}
function getDefineTimeZone($timezone)
{
$userDateTimeZone = new DateTimeZone($timezone);
return new DateTime("now", $userDateTimeZone);
}
function getServerTimeZone()
{
$serverTimeZone = date_default_timezone_get();
$serverDateTimeZone = new DateTimeZone($serverTimeZone);
return new DateTime("now", $serverDateTimeZone);
}
$userDateTime = getDefineTimeZone('America/Curacao');
$serverDateTime = getServerTimeZone();
$timeOffset = serverTimeZone_offset('America/Curacao');
var_dump($userDateTime);
var_dump($serverDateTime);
var_dump($timeOffset); // the seconds is incorrect ?!?!
// adding the timezone difference
$userDateTime->add(new DateInterval('PT'.$timeOffset.'S'));
var_dump($userDateTime);
將輸出:
object(DateTime)[2]
public 'date' => string '2014-10-22 17:36:39' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Curacao' (length=15)
object(DateTime)[3]
public 'date' => string '2014-10-22 23:36:39' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Paris' (length=12)
int 7200
object(DateTime)[2]
public 'date' => string '2014-10-22 19:36:39' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'America/Curacao' (length=15)
這顯然是不正確的。 偏移返回7200秒(僅2小時),而不是21600秒(6小時)。 為什么?
我認為您正在誤解DateTimeZone::getOffset()
的行為。 正如在DateTimeZone php docs中所說的:
此函數將datetime參數中指定的日期/時間的偏移量返回給GMT。 使用所使用的DateTimeZone對象中包含的時區信息來計算GMT偏移量。
因此,如果服務器時區為Europe/Paris
,則getOffset()將返回7200秒,因為Europe / Paris為GMT + 01:00,現在是夏令時,因此為GMT + 02:00。
嘗試改用以下代碼:
function serverTimeZone_offset($userTimeZone)
{
$userDateTimeZone = new DateTimeZone($userTimeZone);
$userDateTime = new DateTime("now", $userDateTimeZone);
$serverTimeZone = date_default_timezone_get();
$serverDateTimeZone = new DateTimeZone($serverTimeZone);
$serverDateTime = new DateTime("now", $serverDateTimeZone);
return $serverDateTimeZone->getOffset($userDateTime) - $userDateTimeZone->getOffset($userDateTime);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.