DateTime 物件導向寫法 (推薦 PHP 5.3+)
$today = new DateTime(); // 當下時間
$yesterday = (clone $today)->modify('-1 day');
$tomorrow = (clone $today)->modify('+1 day');
echo $today->format('Y-m-d'); // 2024-01-15
echo $yesterday->format('Y-m-d');
echo $tomorrow->format('Y-m-d');
// 指定時區
$tz = new DateTimeZone('Asia/Taipei');
$today = new DateTime('now', $tz);
程序式 strtotime() 寫法
echo date('Y-m-d', strtotime('-1 day')); // 昨天
echo date('Y-m-d'); // 今天
echo date('Y-m-d', strtotime('+1 day')); // 明天
// 更精確:以當天 00:00:00 為基準
$todayMidnight = strtotime('today');
$yesterday = date('Y-m-d', $todayMidnight - 86400);
$tomorrow = date('Y-m-d', $todayMidnight + 86400);
常見日期格式化字元
| 字元 | 說明 | 範例 |
| Y | 四位數年份 | 2024 |
| m | 兩位數月份 | 01 |
| d | 兩位數日期 | 15 |
| H | 24小時制時 | 14 |
| i | 分 | 30 |
| s | 秒 | 05 |
| w | 星期 (0=Sunday) | 1 |
| W | 年度週數 | 03 |
實用工具函式
function getDateRange(string $period): array
{
$today = new DateTimeImmutable();
return match ($period) {
'today' => [$today, $today],
'yesterday' => [$today->modify('-1 day'), $today->modify('-1 day')],
'tomorrow' => [$today->modify('+1 day'), $today->modify('+1 day')],
'this_week' => [
$today->modify('monday this week'),
$today->modify('sunday this week')
],
'last_week' => [
$today->modify('monday last week'),
$today->modify('sunday last week')
],
'this_month' => [
$today->modify('first day of this month'),
$today->modify('last day of this month')
],
'last_month' => [
$today->modify('first day of last month'),
$today->modify('last day of last month')
],
default => throw new InvalidArgumentException("Unknown period: $period"),
};
}
// 使用
[$start, $end] = getDateRange('this_month');
echo $start->format('Y-m-d') . ' ~ ' . $end->format('Y-m-d');
效能與快取提示
DateTimeImmutable (PHP 5.5+) 避免副作用,適合函式式程式設計。
- 大量日期運算可考慮
Carbon (Laravel 內建) 或 Chronos (CakePHP) 擴充庫。
- 資料庫查詢日期範圍建議用
WHERE created_at >= '2024-01-01' AND created_at < '2024-02-01' (半開區間),利用索引。