計算兩個日期相差天數看似簡單,實則暗藏時區、夏令時間、閏年等陷阱。本文將從基礎時間戳法進階到現代 DateTime 物件導向做法,並分析各方法優缺點。
<?php
function diffBetweenTwoDays($day1, $day2) {
$second1 = strtotime($day1);
$second2 = strtotime($day2);
// 確保第一個日期較大
if ($second1 < $second2) {
$tmp = $second2;
$second2 = $second1;
$second1 = $tmp;
}
// 86400 = 24 * 60 * 60 秒
return ($second1 - $second2) / 86400;
}
$day1 = "2013-07-27";
$day2 = "2013-08-04";
$diff = diffBetweenTwoDays($day1, $day2);
echo $diff . "\n"; // 輸出 8
?>
strtotime() 依賴預設時區,跨時區計算易出錯<?php
function diffDays(DateTimeInterface $date1, DateTimeInterface $date2): int {
$interval = $date1->diff($date2);
// $interval->days 為總天數(不帶正負號)
// $interval->invert 為 1 表示 $date1 < $date2
return $interval->days;
}
// 使用範例
$date1 = new DateTime('2013-07-27');
$date2 = new DateTime('2013-08-04');
echo diffDays($date1, $date2); // 8
// 支援字串輸入的封裝版
function diffDaysStr(string $day1, string $day2, string $format = 'Y-m-d'): int {
$d1 = DateTime::createFromFormat($format, $day1);
$d2 = DateTime::createFromFormat($format, $day2);
if (!$d1 || !$d2) {
throw new InvalidArgumentException('日期格式錯誤');
}
return $d1->diff($d2)->days;
}
?>
<?php
$start = new DateTime('2024-01-01');
$end = new DateTime('2024-12-31');
$interval = $start->diff($end);
echo "相差 {$interval->y} 年 ";
echo "{$interval->m} 月 ";
echo "{$interval->d} 天\n";
echo "總天數: {$interval->days}\n";
echo "總小時數: {$interval->h + $interval->days * 24}\n";
echo "是否反向: " . ($interval->invert ? '是' : '否') . "\n";
// 格式化輸出
echo $interval->format('%a 天總計'); // %a 為總天數
?>
function countWeekdays(DateTime $start, DateTime $end): int {
$count = 0;
$current = clone $start;
while ($current <= $end) {
$dayOfWeek = (int)$current->format('N'); // 1=週一 ... 7=週日
if ($dayOfWeek < 6) $count++;
$current->modify('+1 day');
}
return $count;
}
function calculateAge(DateTime $birthdate): int {
$today = new DateTime();
$diff = $birthdate->diff($today);
return $diff->y;
}
function isSameDay(DateTime $d1, DateTime $d2): bool {
return $d1->format('Y-m-d') === $d2->format('Y-m-d');
}
| 方法 | 速度 | 記憶體 | 正確性 | 建議場景 |
|---|---|---|---|---|
| strtotime + 除法 | 最快 | 最低 | 低(夏令時間會錯) | 簡單腳本、確定無跨時區/夏令時間 |
| DateTime::diff | 稍慢 | 稍高 | 高(標準庫保證) | 所有正式專案、跨時區、長期維護 |
| Carbon 套件 | 較慢 | 較高 | 最高(功能最豐富) | Laravel 專案、需大量日期運算 |
強烈建議使用 DateTime::diff() 取代時間戳相減法。雖然多建立物件有微小效能成本,但換來的是正確性、可維護性與擴充性。現代 PHP 專案(PHP 7.1+)應將 DateTime 或 DateTimeImmutable 作為日期處理的標準工具,必要時引入 Carbon 等成熟套件簡化複雜日期運算。