時間差異計算是 PHP 開發中極常見的需求:訂單超時判斷、會員到期提醒、文章發布時間顯示、統計報表區間等。本文系統整理多種計算方法,涵蓋從秒級到年級的各種粒度,並分析各方法優缺點與適用場景。
PHP 時間運算基礎是 Unix Timestamp (秒數) —— 從 1970-01-01 00:00:00 UTC 至今的秒數。核心函數:
time():取得目前時間戳strtotime():解析日期字串為時間戳 (支援相對格式如 "+1 day")mktime():由日期元件建立時間戳date():格式化時間戳為字串<?php
$start = strtotime('2011-05-08 07:02:40');
$end = strtotime('2012-12-25 00:00:00');
$diff = $end - $start; // 總秒數差
// 累進換算 (注意:單純除法會有餘數問題)
$days = floor($diff / 86400); // 86400 = 24*3600
$hours = floor(($diff % 86400) / 3600);
$mins = floor(($diff % 3600) / 60);
$secs = $diff % 60;
echo "相差 $days 天 $hours 小時 $mins 分 $secs 秒";
// 輸出:相差 596 天 16 小時 57 分 20 秒
優點:邏輯清晰、易理解。缺點:不考慮閏秒、夏令時間、月份天數不固定,月/年換算不準確。
<?php
$start = new DateTime('2011-05-08 07:02:40');
$end = new DateTime('2012-12-25 00:00:00');
$interval = $start->diff($end); // 回傳 DateInterval 物件
echo "相差 {$interval->y} 年 {$interval->m} 月 {$interval->d} 天 ";
echo "{$interval->h} 小時 {$interval->i} 分 {$interval->s} 秒";
// 輸出:相差 1 年 7 月 17 天 16 小時 57 分 20 秒
// 格式化輸出
echo $interval->format('%y 年 %m 月 %d 天 %h 小時 %i 分 %s 秒');
// 取得總天數 (需 PHP 5.4+)
echo $interval->days; // 596
優點:正確處理月份天數差異、閏年、時區;提供豐富格式化選項。首選方案。
<?php
function monthDiffSimple($date1, $date2)
{
$dt1 = new DateTime($date1);
$dt2 = new DateTime($date2);
return ($dt2->format('Y') - $dt1->format('Y')) * 12
+ ($dt2->format('m') - $dt1->format('m'));
}
echo monthDiffSimple('2012-10-20', '2024-01-15'); // 135 月
<?php
function monthDiffPrecise($start, $end)
{
$start = new DateTime($start);
$end = new DateTime($end);
// 確保 start <= end
if ($start > $end) {
list($start, $end) = [$end, $start];
}
$months = 0;
$current = clone $start;
// 逐月遞增直到超過 end
while ($current <= $end) {
$current->modify('+1 month');
if ($current <= $end) {
$months++;
}
}
return $months;
}
echo monthDiffPrecise('2024-01-31', '2024-02-28'); // 1 月 (非 0)
echo monthDiffPrecise('2024-01-15', '2024-03-14'); // 1 月 (未滿 2 月)
<?php
function dayDiff($date1, $date2)
{
// 統一為 00:00:00 再計算
$d1 = strtotime(date('Y-m-d', strtotime($date1)));
$d2 = strtotime(date('Y-m-d', strtotime($date2)));
return abs($d1 - $d2) / 86400;
}
echo dayDiff('2010-08-11', '2010-08-16'); // 5
echo dayDiff('2010-08-16', '2010-08-11'); // 5 (絕對值)
<?php
function humanTimeDiff($timestamp, $now = null)
{
$now = $now ?? time();
$diff = $now - $timestamp;
if ($diff < 60) return '剛剛';
if ($diff < 3600) return floor($diff/60) . ' 分鐘前';
if ($diff < 86400) return floor($diff/3600) . ' 小時前';
if ($diff < 604800) return floor($diff/86400) . ' 天前';
if ($diff < 2592000) return floor($diff/604800) . ' 週前';
if ($diff < 31536000) return floor($diff/2592000) . ' 個月前';
return floor($diff/31536000) . ' 年前';
}
// 範例
echo humanTimeDiff(strtotime('-30 seconds')); // 剛剛
echo humanTimeDiff(strtotime('-5 minutes')); // 5 分鐘前
echo humanTimeDiff(strtotime('-3 hours')); // 3 小時前
echo humanTimeDiff(strtotime('-2 days')); // 2 天前
echo humanTimeDiff(strtotime('-10 days')); // 1 週前
echo humanTimeDiff(strtotime('-2 months')); // 2 個月前
echo humanTimeDiff(strtotime('-2 years')); // 2 年前
<?php
// composer require nesbot/carbon
use Carbon\Carbon;
$start = Carbon::parse('2011-05-08 07:02:40');
$end = Carbon::parse('2012-12-25 00:00:00');
// 差值物件
$diff = $start->diff($end);
echo $diff->format('%y 年 %m 月 %d 天 %h 時 %i 分 %s 秒');
// 便利方法
echo $start->diffInSeconds($end); // 總秒數
echo $start->diffInMinutes($end); // 總分鐘
echo $start->diffInHours($end); // 總小時
echo $start->diffInDays($end); // 總天數
echo $start->diffInMonths($end); // 總月數
echo $start->diffInYears($end); // 總年數
// 人性化
echo $start->diffForHumans($end); // "1 year ago" (可本地化)
| 陷阱 | 說明 | 解決方案 |
|---|---|---|
| 月份天數不固定 | 單純用 30 天算月份會誤差 | 用 DateTime::diff() 或逐月遞增演算法 |
| 夏令時間 (DST) | 某天可能 23 或 25 小時 | 使用 DateTime 並設定正確時區 |
| 閏秒 | 極少數分鐘有 61 秒 | 一般業務忽略,金融級需用專用時間庫 |
| 時區不一致 | 伺服器/資料庫/使用者時區不同 | 統一儲存 UTC,顯示時轉換使用者時區 |
| strtotime 解析歧義 | "02/03/2024" 美式/英式格式不同 | 統一用 ISO 8601 (YYYY-MM-DD) 或 DateTime::createFromFormat |
humanTimeDiff() 或 Carbon diffForHumans()