PHP Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'UTC' for '8.0/no DST' instead in /path/file.php on line 17
核心原因: PHP 5.1+ 強制要求明確設定時區,否則預設使用 UTC(格林威治時間),與北京時間相差 8 小時。
<?php
// 放在所有 date() 呼叫之前,建議放在入口檔案最頂端
date_default_timezone_set('Asia/Shanghai'); // 或 'PRC'
?>
優點: 部署簡單、跨伺服器一致、不需權限修改 php.ini。缺點: 每個入口點都要加(可用 auto_prepend_file 統一)。
; 找到 [Date] 區段,修改並取消註解 date.timezone = Asia/Shanghai ; 或 date.timezone = PRC
修改後必須重啟 PHP-FPM / Apache 生效。
驗證方式: php -i | grep timezone 或 phpinfo() 查看 date.timezone 值。
| 地區 | 識別碼 | 備註 |
|---|---|---|
| 中國大陸 | Asia/Shanghai | 標準 IANA 時區,推薦使用 |
| 中國大陸 | PRC | 別名,相容舊版 |
| 台灣 | Asia/Taipei | |
| 香港 | Asia/Hong_Kong | |
| 新加坡 | Asia/Singapore | |
| UTC | UTC | 國際標準時間,資料庫儲存建議 |
<?php
// bootstrap.php 或 config/app.php
// 1. 設定 PHP 預設時區(顯示層)
date_default_timezone_set('Asia/Shanghai');
// 2. 資料庫連線時區(儲存層)— 以 MySQL 為例
$pdo = new PDO($dsn, $user, $pass);
$pdo->exec("SET time_zone = '+08:00'"); // 或 'Asia/Shanghai'
// 3. 內部邏輯一律使用 UTC 時間戳 (time()) 或 DateTimeImmutable
// 4. 只在「輸出給使用者看」時轉換為當地時區
function formatForUser(DateTimeInterface $dt, string $format = 'Y-m-d H:i:s'): string {
$dt = clone $dt;
$dt->setTimezone(new DateTimeZone('Asia/Shanghai'));
return $dt->format($format);
}
// 5. API 回傳建議用 ISO 8601 格式(含時區資訊)
echo json_encode(['created_at' => (new DateTime())->format(DateTime::ATOM)]);
// {"created_at":"2024-01-15T14:30:00+08:00"}
DateTime 會自動處理php -r "echo date_default_timezone_get();" 確認 CLI 時區php -r "echo ini_get('date.timezone');" 確認 php.ini 設定php-fpm / apache 是否重啟date_default_timezone_set()Asia/Shanhai 少一個 g)