部署於海外主機(如 GoDaddy)的專案常需將伺服器時間轉換為目標時區(如 Asia/Shanghai)。使用 PHP 內建 DateTime 與 DateTimeZone 類別,能優雅處理夏令時、閏秒等複雜規則。
/**
* 將指定時區的時間字串轉換為目標時區
*
* @param string $src_time 源時間字串,格式需與 $format 參數一致
* @param string $from_tz 源時區標識符,如 'America/Denver'
* @param string $to_tz 目標時區標識符,如 'Asia/Shanghai'
* @param string $format 輸出格式,預設 'Y-m-d H:i:s'
* @return string|false 轉換後的時間字串,失敗返回 false
*/
function convert_timezone(
string $src_time,
string $from_tz = 'America/Denver',
string $to_tz = 'Asia/Shanghai',
string $format = 'Y-m-d H:i:s'
): string|false {
try {
$dt = new DateTime($src_time, new DateTimeZone($from_tz));
$dt->setTimezone(new DateTimeZone($to_tz));
return $dt->format($format);
} catch (Exception $e) {
error_log("Timezone conversion failed: {$e->getMessage()}");
return false;
}
}
// 美東時間轉北京時間
$us_time = '2024-03-10 02:30:00'; // 夏令時生效前
echo convert_timezone($us_time, 'America/New_York', 'Asia/Shanghai');
// 輸出: 2024-03-10 15:30:00 (相差 13 小時)
$us_time_dst = '2024-07-10 02:30:00'; // 夏令時期間
echo convert_timezone($us_time_dst, 'America/New_York', 'Asia/Shanghai');
// 輸出: 2024-07-10 14:30:00 (相差 12 小時,自動處理 DST)
高頻調用時可快取 DateTimeZone 物件:
class TimezoneConverter {
private array $zone_cache = [];
private function get_zone(string $tz): DateTimeZone {
return $this->zone_cache[$tz] ??= new DateTimeZone($tz);
}
public function convert(string $time, string $from, string $to, string $fmt = 'Y-m-d H:i:s'): string|false {
try {
$dt = new DateTime($time, $this->get_zone($from));
$dt->setTimezone($this->get_zone($to));
return $dt->format($fmt);
} catch (Exception $e) {
return false;
}
}
}
| 地區 | 標識符 | 備註 |
|---|---|---|
| 中國大陸 | Asia/Shanghai | 無夏令時 |
| 香港/台灣 | Asia/Hong_Kong / Asia/Taipei | 同上 |
| 美國東部 | America/New_York | 含 DST |
| 美國西部 | America/Los_Angeles | 含 DST |
| 歐洲中部 | Europe/Berlin | 含 DST |
| UTC | UTC | 基準時區 |
time() 或 DATE_TIMESTAMP),顯示層再轉換。善用 DateTime 物件,讓跨時區業務邏輯更健壯、可維護。