首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP date() 警告:時區設置錯誤完美解決方案(date.timezone / date_default_timezone_set)

     編輯:PHP 相關知識

錯誤現場

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.
We selected 'UTC' for '8.0/no DST' instead...

原因:PHP 默認使用 UTC 時間,與北京時間相差 8 小時。

方案一:代碼級設置(推薦,項目可控)

在入口文件(如 index.php、common.php)最頂部加入:

<?php
date_default_timezone_set('PRC'); // 或 'Asia/Shanghai'
?>

PRC 代表中華人民共和國,等同於 Asia/Shanghai,涵蓋中國大陸標準時間。

方案二:配置文件級設置(全局生效,需服務器權限)

  1. 打開 php.ini
  2. 找到 ;date.timezone =(分號表示註釋)
  3. 修改為:date.timezone = PRC
  4. 重啟 Apache / PHP-FPM

時區標識符速查

標識符含義適用範圍
PRC中華人民共和國中國大陸(推薦)
Asia/Shanghai上海/北京時間中國大陸、港澳台
Asia/Hong_Kong香港時間香港特別行政區
Asia/Taipei台北時間台灣地區
UTC協調世界時國際標準、服務器日誌

進階:DateTime 物件風格

$dt = new DateTime('now', new DateTimeZone('PRC'));
echo $dt->format('Y-m-d H:i:s');

// 或動態修改
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('Y-m-d H:i:s'); // 輸出 UTC 時間

避坑提醒

  • 拼寫錯誤(如 PRC 寫成 PPC)會導致回退到 UTC 並再次拋出警告。
  • Windows 版 PHP 5.3+ 才支持 PRC,舊版請用 Asia/Shanghai。
  • 框架(Laravel/ThinkPHP/Yii)通常在配置文件集中設置時區,避免分散在業務代碼中。

延伸閱讀

  • PHP Maximum execution time of 30 seconds exceeded 解決
  • phpMyAdmin Cannot start session without errors 解決
  • PHP Call to undefined function curl_init() 解決
  • select into from Undeclared variable 錯誤排查
  • DedeCMS DedeTag Engine Create File False 錯誤
  • Firefox event is not defined 錯誤
  • Fatal error: Class 'SoapClient' not found
  • XDebug 進度條卡 57% waiting for XDebug session
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved