日期差值計算核心在於統一轉換為 Unix 時間戳,再以秒數除以一天秒數 (86400) 取絕對值並向上取整。
<?php
function getDateDiff($date1, $date2) {
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
if ($ts1 === false || $ts2 === false) {
throw new InvalidArgumentException('Invalid date format');
}
return (int)ceil(abs($ts1 - $ts2) / 86400);
}
// 使用範例
echo getDateDiff('2024-01-01', '2024-01-10'); // 9
echo getDateDiff('2024-12-31', '2025-01-01'); // 1 (跨年)
strtotime 支援多種格式:Y-m-d、Y/m/d、+1 week 等。abs() 確保正差值,ceil() 處理非整日差值 (如 23 小時 → 1 天)。strtotime(date('Y-m-d', $ts))。<?php
function getDateDiffOOP($date1, $date2) {
$dt1 = new DateTime($date1);
$dt2 = new DateTime($date2);
$interval = $dt1->diff($dt2);
return (int)$interval->days; // 已為絕對天數
}
// 含時區、夏令時自動處理,更健壯
strtotime 版本極快,適合高頻呼叫;DateTime::diff 功能豐富 (支援年/月/日/時/分/秒差值、反轉、格式化),適合複雜業務邏輯。