32 位系統有符號整數最大值 2147483647 對應 2038-01-19 03:14:07 UTC。PHP 早期版本在 32 位構建上,time()、strtotime()、date() 等函數基於 32 位 time_t,超出範圍返回 false 或錯誤結果。64 位 PHP (目前主流) 已原生支援 64 位時間戳 (可表示至 2920 億年),但代碼若需跨平台或兼容舊環境,仍需安全封裝。
DateTime 內部使用 64 位整數 (或浮點數) 存儲時間戳,全平台無 2038 問題。直接使用 DateTime 替代傳統函數。
<?php
/**
* 安全 strtotime:支援 64 位時間戳、DateTime 字符串、相對時間
* @param string $time 時間字符串 (同 strtotime)
* @param int $now 基準時間戳 (可選)
* @return int|false 時間戳 (64 位整數),失敗 false
*/
function safeStrtotime(string $time, int $now = 0): int|false {
try {
$dt = new DateTime($time, new DateTimeZone(date_default_timezone_get()));
if ($now > 0) {
$dt->setTimestamp($now);
$dt->modify($time); // 相對時間基於 $now
}
return $dt->getTimestamp(); // 返回 64 位整數 (PHP 7.1+ 返回 int)
} catch (Exception $e) {
return false;
}
}
/**
* 安全 date:支援 64 位時間戳格式化
* @param string $format 格式字符串 (同 date)
* @param int $timestamp 64 位時間戳
* @return string 格式化日期
*/
function safeDate(string $format, int $timestamp): string {
try {
$dt = new DateTime('@' . $timestamp);
$dt->setTimezone(new DateTimeZone(date_default_timezone_get()));
return $dt->format($format);
} catch (Exception $e) {
return '';
}
}
/**
* 獲取當前 64 位時間戳
*/
function safeTime(): int {
return (new DateTime())->getTimestamp();
}
// ===== 測試 2038 後日期 =====
$future = '2050-01-01 00:00:00';
$ts = safeStrtotime($future);
echo "2050 時間戳: $ts\n"; // 2524608000 (超過 2147483647)
echo "格式化: " . safeDate('Y-m-d H:i:s', $ts) . "\n"; // 2050-01-01 00:00:00
// 相對時間
echo safeDate('Y-m-d', safeStrtotime('+10 years', safeStrtotime('2030-01-01'))); // 2040-01-01
DateTime('@' . $timestamp):@ 前綴表示 UNIX 時間戳構造,支援 64 位整數。getTimestamp():PHP 7.1+ 返回 int (64 位),舊版返回 float,建議 (int) 強轉。setTimezone():確保輸出時區與 date_default_timezone_get() 一致,避免時區偏移。Exception,統一返回 false/'' 兼容舊代碼邏輯。| PHP 版本 | 架構 | time() 範圍 | DateTime 範圍 | 建議 |
|---|---|---|---|---|
| 5.2 - 5.6 | 32 位 | 1901-2038 | 完整 64 位 | 必須用 DateTime |
| 5.2 - 5.6 | 64 位 | 完整 64 位 | 完整 64 位 | 原生函數可用 |
| 7.0 - 8.3 | 64 位 (主流) | 完整 64 位 | 完整 64 位 | 原生函數可用,DateTime 更強大 |
strtotime( → safeStrtotime(,date( → safeDate( (或直接改用 DateTime 面向對象風格)。TIMESTAMP 字段 (1970-2038) → 改為 DATETIME (1000-9999) 或 BIGINT 存儲 64 位時間戳。2038 年問題在 64 位 PHP 上已不存在,但為代碼可移植性、歷史數據兼容、團隊統一規範,建議全項目統一使用 DateTime 類或封裝 safeStrtotime/safeDate 兼容函數。棄用 date()/strtotime() 直接處理 2038 後日期的代碼。