日期字串 → strtotime() / DateTime → Unix Timestamp(秒) → 數學運算 → 格式化輸出。
<?php
$date1 = '2024-01-15';
$date2 = '2023-01-14';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$diffSeconds = $ts1 - $ts2;
$diffDays = round($diffSeconds / 86400); // 86400 = 24*3600
echo "相差 $diffDays 天\n"; // 輸出 366 天(含閏年)
// 更精確:floor 向下取整(不足一天不算)
$diffDays = floor($diffSeconds / 86400);
?>
<?php
$dt1 = new DateTime('2024-01-15');
$dt2 = new DateTime('2023-01-14');
$interval = $dt1->diff($dt2); // 回傳 DateInterval 物件
echo "相差 {$interval->days} 天\n"; // 總天數
echo "相差 {$interval->y} 年 {$interval->m} 月 {$interval->d} 天\n"; // 年月日拆解
echo "相差 {$interval->h} 時 {$interval->i} 分 {$interval->s} 秒\n"; // 時分秒
// 格式化輸出
echo $interval->format('%a 天 %h 小時 %i 分鐘'); // %a = 總天數
new DateTime('2024-01-15', new DateTimeZone('Asia/Taipei')),避免伺服器時區導致計算偏差。new DateTime('+1 week')、new DateTime('first day of next month')。DateTimeImmutable 方法回傳新物件,避免副作用,適合函數式風格。DateTime::createFromFormat('Y-m-d H:i:s.u', $str)。| 函式 | 用途 | 範例 |
|---|---|---|
checkdate(m,d,Y) | 驗證日期合法性 | checkdate(2,29,2024) → true |
getdate(ts?) | 取得日期/時間陣列 | getdate()['mon'] → 當前月份 |
mktime(h,i,s,m,d,Y) | 建立 timestamp | mktime(0,0,0,1,1,2024) |
date(fmt, ts?) | 格式化輸出 | date('Y-m-d H:i:s') |
strtotime(str) | 字串轉 timestamp | strtotime('next Monday') |
strftime(fmt, ts) | 區域化格式化 | setlocale(LC_TIME,'zh_TW'); strftime('%Y年%m月') |
microtime(true) | 高精度浮點秒數 | 效能測量 $end-$start |
gmdate/gmmktime | GMT/UTC 時間 | 跨時區系統同步基準 |
date_default_timezone_set/get | 設定/取得預設時區 | date_default_timezone_set('Asia/Taipei') |
date_default_timezone_set('Asia/Taipei') 或 php.ini 設定 date.timezone。DateTime::diff(),勿直接除 86400。strtotime() 回傳有號 32 位整數,最大 2038-01-19。64 位 PHP 或 DateTime 無此限制。strtotime('+1 month', '2024-01-31') → 2024-03-02(非 2/29),業務邏輯需自行處理「月底對齊」。strtotime(),物件建立開銷較大。掌握 strtotime() 快速計算與 DateTime 精準操控雙技能,應對所有日期比較業務場景。