萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP gmdate() 函數詳解:將 UNIX 時間戳格式化為 GMT/UTC 時間

函數簡介

gmdate() 與 date() 用法完全相同,唯一區別:**返回的時間始終為 GMT/UTC 時間**,不受服務器時區設置影響。適用於日誌記錄、API 時間戳標準化、跨時區系統同步等場景。

語法與參數

gmdate(string $format, ?int $timestamp = null): string
  • $format:格式化字串,參考 DateTime 格式字元
  • $timestamp:可選 UNIX 時間戳(秒),預設為當前時間 time()
  • 返回:格式化後的 GMT 時間字串

常用格式字元速查

字元說明範例輸出
Y4位數年份2024
m月份(01-12)01
d日期(01-31)15
H24小時制(00-23)14
i分鐘(00-59)30
s秒(00-59)59
rRFC 2822 格式Mon, 15 Jan 2024 14:30:59 +0000
cISO 8601 格式2024-01-15T14:30:59+00:00
UUNIX 時間戳1705330259
O時區偏移量+0000
T時區縮寫GMT
L是否閏年1/0

實戰代碼範例

<?php
// 設置腳本時區(不影響 gmdate 輸出)
date_default_timezone_set('Asia/Shanghai');

echo "=== gmdate() 格式化示例 ===\n";
echo "當前 GMT 時間 (RFC 2822): " . gmdate('r') . "\n";
echo "當前 GMT 日期 (完整): " . gmdate('F j, Y') . "\n";      // January 15, 2024
echo "當前 GMT 日期 (縮寫): " . gmdate('M j, Y') . "\n";      // Jan 15, 2024
echo "當前 GMT 日期 (數字): " . gmdate('m/d/y') . "\n";       // 01/15/24
echo "當前 GMT 日期 (序數): " . gmdate('jS of M, Y') . "\n";  // 15th of Jan, 2024
echo "當前 GMT 時間 (12制): " . gmdate('g:i:s A T') . "\n";   // 2:30:59 PM GMT
echo "當前 GMT 時間 (24制): " . gmdate('H:i:s O') . "\n";     // 14:30:59 +0000

// 指定時間戳
$ts = strtotime('2024-01-01 00:00:00');
echo "\n指定時間戳 {$ts}:\n";
echo gmdate('Y-m-d H:i:s', $ts) . " GMT\n";

// 閏年判斷
$year = 2024;
echo "\n{$year} 年 " . (gmdate('L', strtotime("{$year}-01-01")) ? '是' : '不是') . " 閏年\n";

// 從紀元至今秒數
echo "\n自 1970-01-01 以來秒數: " . time() . "\n";
?>

輸出結果示例(假設當前 GMT 為 2024-01-15 14:30:59)

=== gmdate() 格式化示例 ===
當前 GMT 時間 (RFC 2822): Mon, 15 Jan 2024 14:30:59 +0000
當前 GMT 日期 (完整): January 15, 2024
當前 GMT 日期 (縮寫): Jan 15, 2024
當前 GMT 日期 (數字): 01/15/24
當前 GMT 日期 (序數): 15th of Jan, 2024
當前 GMT 時間 (12制): 2:30:59 PM GMT
當前 GMT 時間 (24制): 14:30:59 +0000

指定時間戳 1704067200:
2024-01-01 00:00:00 GMT

2024 年 是 閏年

自 1970-01-01 以來秒數: 1705330259

gmdate() vs date() 關鍵差異

<?php
date_default_timezone_set('Asia/Shanghai'); // UTC+8

$ts = time();

echo "date()  (本地時間): " . date('Y-m-d H:i:s T', $ts) . "\n";
// 2024-01-15 22:30:59 CST

echo "gmdate() (GMT 時間): " . gmdate('Y-m-d H:i:s T', $ts) . "\n";
// 2024-01-15 14:30:59 GMT

// 兩者相差 8 小時(時區偏移)
?>

實際應用場景

1. API 統一返回 UTC 時間

// 控制器/服務層
return response()->json([
    'data' => $data,
    'timestamp' => gmdate('c'), // ISO 8601: 2024-01-15T14:30:59+00:00
    'timestamp_unix' => time(),
]);

2. 資料庫存儲統一時區

// MySQL TIMESTAMP 欄位自動轉換,但 DATETIME 不轉換
// 寫入前統一轉為 UTC
$stmt = $pdo->prepare('INSERT INTO logs (created_at) VALUES (?)');
$stmt->execute([gmdate('Y-m-d H:i:s')]);

3. 跨時區任務調度

// Cron 表達式通常基於服務器時區
// 若需在「每天 UTC 00:00」執行,需換算為服務器時區
// 或使用 gmdate 判斷當前 UTC 時間
if (gmdate('H:i') === '00:00') {
    // 執行每日 UTC 零點任務
}

4. 日誌系統統一時間戳

function logMessage(string $level, string $message): void {
    $entry = sprintf(
        "[%s] [%s] %s\n",
        gmdate('Y-m-d H:i:s'), // 統一 GMT
        strtoupper($level),
        $message
    );
    file_put_contents('/var/log/app.log', $entry, FILE_APPEND);
}

注意事項

  • Windows PHP 5.3 之前:`gmdate()` 在 Windows 上可能因缺少 `tzdata` 返回錯誤時間,現代版本(PHP 7.0+)已修復。
  • 夏令時:GMT/UTC 無夏令時,`gmdate()` 全年固定偏移 0,極適合作為基準時間。
  • DateTime 物件導向替代:現代代碼推薦使用 `new DateTime('@' . $ts, new DateTimeZone('UTC'))->format('c')`,功能更強大(時區轉換、運算、比較)。

總結

gmdate() 是 PHP 處理標準化 UTC 時間的輕量級工具。掌握其格式字元、與 `date()` 的時區差異、以及在 API、資料庫、日誌、定時任務中的標準化應用,是構建可靠分佈式系統的基礎技能。新專案建議優先使用 DateTimeImmutable 類別獲得更豐富的功能與不可變性保證。

copyright © 萬盛學電腦網 all rights reserved