舊式 date() + mktime() 易出錯且難閱讀,DateTime 物件導向介面更直觀、可鏈式操作、支援時區。
<?php
$today = new DateTime(); // 現在
$yesterday = (clone $today)->modify('-1 day');
$tomorrow = (clone $today)->modify('+1 day');
echo '昨天:' . $yesterday->format('Y-m-d') . PHP_EOL;
echo '今天:' . $today->format('Y-m-d') . PHP_EOL;
echo '明天:' . $tomorrow->format('Y-m-d') . PHP_EOL;
function getYesterday(): string {
return (new DateTime('-1 day'))->format('Y-m-d');
}
function getToday(): string {
return (new DateTime())->format('Y-m-d');
}
function getTomorrow(): string {
return (new DateTime('+1 day'))->format('Y-m-d');
}
$tz = new DateTimeZone('Asia/Taipei');
$today = new DateTime('now', $tz);
$yesterday = (clone $today)->modify('-1 day');
// 或
$yesterday = new DateTime('-1 day', $tz);
| 字串 | 含義 |
|---|---|
+1 day / -1 day | 後/前一天 |
+1 week / -1 week | 後/前一週 |
first day of this month | 本月 1 號 |
last day of next month | 下月最後一天 |
monday this week | 本週一 |
$today->modify('-1 day') 再用 $today,會改變原物件 → 使用 clone。date('Y-m-d', strtotime('-1 day')),strtotime 在 32 位系統 2038 年後失效,且 DST 切換日易誤差。DateTime 物件建立極輕量,單次請求建立幾十個完全無負擔。若極度追求效能(如批次處理百萬筆),可用 date() + 時間戳,但需自行處理時區與 DST。
// 現代標準寫法
$yesterday = (new DateTime('-1 day'))->format('Y-m-d');
$today = (new DateTime())->format('Y-m-d');
$tomorrow = (new DateTime('+1 day'))->format('Y-m-d');
簡潔、安全、可維護,請全面棄用 mktime/strtotime 組合。