PHP 日期時間比較常見錯誤:字串直接比較、忽略時區、混用 strtotime/date。本文建立正確觀念:統一使用 DateTime 物件、內部儲存 UTC、顯示時轉換時區,並示範差值計算、範圍判斷、業務邏輯常用場景。
<?php
// 建立 DateTime (預設系統時區)
$dt1 = new DateTime('2024-01-15 14:30:00');
$dt2 = new DateTime('now'); // 當前時間
// 指定時區建立
$tzTaipei = new DateTimeZone('Asia/Taipei');
$dt3 = new DateTime('2024-01-15 14:30:00', $tzTaipei);
// 從時間戳建立
$dt4 = (new DateTime())->setTimestamp(1705312200); // 2024-01-15 14:30:00 UTC
// 格式化輸出
echo $dt1->format('Y-m-d H:i:s'); // 2024-01-15 14:30:00
echo $dt1->format('Y/m/d'); // 2024/01/15
echo $dt1->format('U'); // Unix timestamp
// 修改時區 (不改變時間點,只改顯示)
$dt1->setTimezone($tzTaipei);
echo $dt1->format('Y-m-d H:i:s T'); // 2024-01-15 22:30:00 CST
// DateTimeImmutable (PHP 5.5+) - 所有修改回傳新物件,原物件不變
$immutable = new DateTimeImmutable('2024-01-15 14:30:00', $tzTaipei);
$nextDay = $immutable->modify('+1 day'); // 回傳新物件
echo $immutable->format('Y-m-d'); // 仍是 2024-01-15
echo $nextDay->format('Y-m-d'); // 2024-01-16
?>
<?php
$dt1 = new DateTime('2024-01-15 10:00:00', new DateTimeZone('UTC'));
$dt2 = new DateTime('2024-01-15 18:00:00', new DateTimeZone('Asia/Taipei')); // 同一時間點
var_dump($dt1 == $dt2); // true (比較時間點)
var_dump($dt1 === $dt2); // false (不同物件)
var_dump($dt1 < $dt2); // false
var_dump($dt1 > $dt2); // false
// 不同時區但不同時間點
$dt3 = new DateTime('2024-01-15 10:00:00', new DateTimeZone('UTC'));
$dt4 = new DateTime('2024-01-15 10:00:00', new DateTimeZone('Asia/Taipei')); // 早 8 小時
var_dump($dt3 < $dt4); // true (dt3 時間點較早)
?>
<?php
$start = new DateTime('2024-01-01 00:00:00');
$end = new DateTime('2024-01-15 14:30:00');
$diff = $start->diff($end); // 回傳 DateInterval 物件
echo "相差 {$diff->y} 年 {$diff->m} 月 {$diff->d} 天 ";
echo "{$diff->h} 時 {$diff->i} 分 {$diff->s} 秒<br>";
// 總天數 (需用 days 屬性,非 d)
echo "總天數: {$diff->days}<br>"; // 14
// 總秒數
$totalSeconds = $end->getTimestamp() - $start->getTimestamp();
echo "總秒數: {$totalSeconds}<br>";
// 易讀格式
function formatDuration(DateInterval $diff) {
$parts = [];
if ($diff->y) $parts[] = "{$diff->y}年";
if ($diff->m) $parts[] = "{$diff->m}月";
if ($diff->d) $parts[] = "{$diff->d}天";
if ($diff->h) $parts[] = "{$diff->h}時";
if ($diff->i) $parts[] = "{$diff->i}分";
if ($diff->s) $parts[] = "{$diff->s}秒";
return implode(' ', $parts) ?: '0秒';
}
echo formatDuration($diff); // 14天 14時 30分 0秒
?>
<?php
function isDateInRange($dateStr, $startStr, $endStr, $timezone = 'UTC') {
$tz = new DateTimeZone($timezone);
$date = new DateTime($dateStr, $tz);
$start = new DateTime($startStr, $tz);
$end = new DateTime($endStr, $tz);
// 含邊界:開始 <= 日期 <= 結束
return $start <= $date && $date <= $end;
}
// 使用
var_dump(isDateInRange('2024-01-15', '2024-01-01', '2024-01-31')); // true
var_dump(isDateInRange('2024-02-01', '2024-01-01', '2024-01-31')); // false
?>
<?php
function calculateAge($birthDateStr, $referenceDateStr = 'now') {
$birth = new DateTime($birthDateStr);
$ref = new DateTime($referenceDateStr);
$diff = $birth->diff($ref);
return $diff->y;
}
echo calculateAge('1990-05-20'); // 依當前日期計算
?>
<?php
function countBusinessDays(DateTime $start, DateTime $end) {
$count = 0;
$current = clone $start;
while ($current <= $end) {
$dayOfWeek = (int)$current->format('N'); // 1=Mon ... 7=Sun
if ($dayOfWeek < 6) $count++; // 1-5 為工作日
$current->modify('+1 day');
}
return $count;
}
$start = new DateTime('2024-01-01');
$end = new DateTime('2024-01-31');
echo "營業日: " . countBusinessDays($start, $end); // 23 (視假日而定)
?>
<?php
function timeAgo(DateTime $dt, $now = null) {
$now = $now ?? new DateTime();
$diff = $now->getTimestamp() - $dt->getTimestamp();
if ($diff < 60) return "{$diff}秒前";
if ($diff < 3600) return floor($diff/60) . "分鐘前";
if ($diff < 86400) return floor($diff/3600) . "小時前";
if ($diff < 604800) return floor($diff/86400) . "天前";
return $dt->format('Y-m-d');
}
echo timeAgo(new DateTime('-5 minutes')); // 5分鐘前
echo timeAgo(new DateTime('-3 hours')); // 3小時前
echo timeAgo(new DateTime('-2 days')); // 2天前
echo timeAgo(new DateTime('2023-12-01')); // 2023-12-01
?>
<?php
// 1. 系統預設時區 (php.ini 或程式設定)
date_default_timezone_set('Asia/Taipei'); // 或 'UTC'
// 2. 資料庫連線設定時區 (MySQL)
$pdo->exec("SET time_zone = '+00:00'"); // 連線層面設為 UTC
// 3. 使用者偏好時區儲存於用戶表
// users.timezone = 'Asia/Taipei'
// 4. 顯示時轉換
function formatForUser(DateTime $dt, string $userTimezone, string $format = 'Y-m-d H:i:s') {
$dt = clone $dt;
$dt->setTimezone(new DateTimeZone($userTimezone));
return $dt->format($format);
}
// 5. 接收前端傳入時間:前端傳 ISO 8601 含時區 (2024-01-15T14:30:00+08:00)
$input = $_POST['datetime'] ?? '';
$dt = new DateTime($input); // 自動解析時區偏移
$dt->setTimezone(new DateTimeZone('UTC')); // 統一存儲為 UTC
?>
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
| if ('2024-01-15' > '2024-01-01') | 字串字典序比較,非日期大小 | new DateTime('2024-01-15') > new DateTime('2024-01-01') |
| strtotime('2024-01-15') > time() | time() 回傳 UTC 時間戳,strtotime 解析依賴預設時區 | 統一用 DateTime 物件比較 |
| date('Y-m-d') 比較 | 字串比較,且無時區資訊 | new DateTime() 比較 |
| diff->d 取得總天數 | d 只回傳「天」部分 (不含月年換算) | 用 diff->days 或 timestamp 相減 |
| modify('+1 month') 日期邊界問題 | 1/31 +1 month = 3/3 (非 2/28) | 用 modify('first day of +1 month') 或 Calendar 類別 |