getTimezoneOffset()) 與是否夏令時。customer_timezone, inDaylightTime)。<script>
window.addEventListener('load', function() {
var now = new Date();
// 時區偏移 (分鐘),東半球為負,西半球為正 → 取反得時區
var tzOffset = -now.getTimezoneOffset() / 60; // 如 +8
setCookie('customer_timezone', tzOffset, 365);
// 簡易夏令時偵測:比較 1/1 與 7/1 時差
var jan = new Date(now.getFullYear(), 0, 1);
var jul = new Date(now.getFullYear(), 6, 1);
var stdOffset = Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
var isDST = now.getTimezoneOffset() < stdOffset;
setCookie('inDaylightTime', isDST ? 1 : 0, 365);
});
function setCookie(name, value, days) {
var exp = new Date();
exp.setTime(exp.getTime() + days * 86400000);
document.cookie = name + '=' + encodeURIComponent(value) + ';expires=' + exp.toGMTString() + ';path=/';
}
</script>
<?php
/**
* 將 GMT 時間戳轉換為使用者本地時間 (H:i)
*/
function gmt_to_local($gmtTimestamp = '') {
if ($gmtTimestamp === '') $gmtTimestamp = time();
$tz = isset($_COOKIE['customer_timezone']) ? (float)$_COOKIE['customer_timezone'] : 0;
$dst = isset($_COOKIE['inDaylightTime']) && $_COOKIE['inDaylightTime'] == 1;
$local = $gmtTimestamp + $tz * 3600;
if ($dst) $local += 3600; // 夏令時再加 1 小時
return date('H:i', $local);
}
// 使用範例
echo '伺服器時間: ' . date('H:i') . '<br>';
echo '您的本地時間: ' . gmt_to_local() . '<br>';
<?php
function gmt_to_local_full($gmtTimestamp, $format = 'Y-m-d H:i:s') {
$tz = isset($_COOKIE['customer_timezone']) ? (float)$_COOKIE['customer_timezone'] : 0;
$dst = isset($_COOKIE['inDaylightTime']) && $_COOKIE['inDaylightTime'] == 1;
$local = $gmtTimestamp + $tz * 3600 + ($dst ? 3600 : 0);
return date($format, $local);
}
// 資料庫儲存 UTC 時間 (TIMESTAMP 或 DATETIME + 時區欄位)
// 顯示時:
echo gmt_to_local_full($model->created_at, 'Y-m-d H:i:s T');
<?php
// 前端傳送 IANA 時區名稱 (如 Asia/Taipei)
$tzName = $_COOKIE['user_timezone'] ?? 'UTC';
$dt = new DateTime('@' . $gmtTimestamp); // UTC
$dt->setTimezone(new DateTimeZone($tzName));
echo $dt->format('Y-m-d H:i:s');
優點:自動處理夏令時歷史規則、時區資料庫更新、格式化本地化。
domain=.example.com。