萬盛學電腦網

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

PHP 日期時間函數完全手冊:mktime、date、strtotime、DateTime 物件導向用法大全

核心函數速查表

函數用途回傳值適用場景
time()當前 Unix 時間戳int快速取得當前秒數
mktime(h,m,s,mon,day,year)組合日期時間產生時間戳 (本地時區)int|false固定日期計算、生日轉換
gmmktime(...)組合 GMT 日期時間產生時間戳int|false跨時區計算、儲存標準時間
date(format, ts)格式化本地時間戳為字串string顯示日期、日誌記錄
gmdate(format, ts)格式化 GMT 時間戳stringAPI 回傳、國際化標準時間
strtotime(time_str)解析英文文字日期為時間戳int|false使用者輸入解析、相對時間計算
strftime(format, ts)依 locale 格式化 (需 setlocale)string多語系日期顯示
microtime(true)微秒級時間戳 (float)float效能測量、高精度計時
checkdate(m,d,y)驗證日期合法性bool表單驗證、資料清洗
getdate(ts)時間戳轉關聯陣列array需分離年月日時分秒時

實戰範例集

1. 基本格式化輸出

<?php
// 當前時間 (中國時區 UTC+8)
date_default_timezone_set('Asia/Taipei');
echo date("Y-m-d H:i:s");           // 2024-12-25 14:30:00
echo date("Y/m/d l");               // 2024/12/25 Wednesday
echo date("Y年m月d日 H點i分");       // 2024年12月25日 14點30分
?>

2. 固定日期時間戳轉換

<?php
$ts = mktime(13, 15, 23, 6, 7, 2006); // 2006-06-07 13:15:23 本地時間
echo date("Y-m-d H:i:s", $ts);

$gmt_ts = gmmktime(12, 25, 23, 7, 9, 2006); // GMT 時間
echo gmdate("Y-m-d H:i:s", $gmt_ts);
?>

3. 相對時間計算 (strtotime 強項)

<?php
echo date("Y-m-d", strtotime("today"));        // 今天
echo date("Y-m-d", strtotime("tomorrow"));     // 明天
echo date("Y-m-d", strtotime("+3 days"));      // 3 天后
echo date("Y-m-d", strtotime("next Monday"));  // 下週一
echo date("Y-m-d", strtotime("first day of next month")); // 下月1號
echo date("Y-m-d", strtotime("-1 month"));     // 一個月前
?>

4. 多語系日期 (strftime + setlocale)

<?php
setlocale(LC_TIME, 'zh_TW.utf8'); // Linux
// setlocale(LC_TIME, 'cht');      // Windows
echo strftime("%Y年%B%d日 %A");   // 2024年十二月25日 星期三
?>

5. 效能測量

<?php
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) { $x = $i * $i; }
$end = microtime(true);
printf("耗時: %.4f 秒", $end - $start);
?>

現代最佳實務:DateTime 物件導向介面 (PHP 5.2+)

<?php
$dt = new DateTime('now', new DateTimeZone('Asia/Taipei'));
echo $dt->format('Y-m-d H:i:s');

$dt->modify('+1 week');
echo $dt->format('Y-m-d');

$diff = $dt->diff(new DateTime('now'));
echo $diff->format('%a 天 %h 小時 %i 分鐘');

// 不可變版本 (PHP 5.5+)
$immutable = new DateTimeImmutable('now');
$nextWeek = $immutable->modify('+1 week'); // 回傳新實例
?>

時區設定最佳實務

  1. php.ini:date.timezone = "Asia/Taipei" (最高優先級)
  2. 腳本開頭:date_default_timezone_set('Asia/Taipei')
  3. DateTime 建構子傳入 DateTimeZone 物件

避免: 手動加減 8*3600 秒,夏令時間會導致錯誤。

copyright © 萬盛學電腦網 all rights reserved