PHP 透過 mktime(時, 分, 秒, 月, 日, 年) 產生 Unix 時間戳,配合 date() 取得當前日期元件,即可精確計算各時間區間邊界。
<?php
$now = time();
// 今日 00:00:00
$todayStart = mktime(0, 0, 0, date('m', $now), date('d', $now), date('Y', $now));
// 今日 23:59:59
$todayEnd = mktime(23, 59, 59, date('m', $now), date('d', $now), date('Y', $now));
// 更簡潔寫法:明日 00:00:00 減 1 秒
$todayEnd = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
?>
| 區間 | 起始時間戳 | 結束時間戳 |
|---|---|---|
| 今日 | mktime(0,0,0,date('m'),date('d'),date('Y')) |
mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1 |
| 昨日 | mktime(0,0,0,date('m'),date('d')-1,date('Y')) |
mktime(0,0,0,date('m'),date('d'),date('Y'))-1 |
| 本週(週一起) | mktime(0,0,0,date('m'),date('d')-date('w')+1,date('Y')) |
mktime(23,59,59,date('m'),date('d')-date('w')+7,date('Y')) |
| 上週 | mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y')) |
mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y')) |
| 本月 | mktime(0,0,0,date('m'),1,date('Y')) |
mktime(23,59,59,date('m'),date('t'),date('Y')) |
date('w'):星期幾(0=週日, 1=週一...6=週六)date('t'):當月總天數(28-31)date('m')、date('d')、date('Y'):月、日、四位數年份<?php
$today = new DateTime('today'); // 今日 00:00:00
$tomorrow = clone $today;
$tomorrow->modify('+1 day'); // 明日 00:00:00
$todayStart = $today->getTimestamp();
$todayEnd = $tomorrow->getTimestamp() - 1;
// 本月第一天
$monthStart = new DateTime('first day of this month');
// 本月最後一天 23:59:59
$monthEnd = new DateTime('last day of this month 23:59:59');
?>
DateTime 類別提供更直觀的字串解析、時區支援與不可變操作(DateTimeImmutable),現代專案建議優先使用。
date_default_timezone_set('Asia/Taipei')modify('+1 day')created_at BETWEEN $start AND $end$expire = $todayEnd - time()掌握 mktime() 與 date() 組合技巧,能快速產生各類時間區間邊界。現代專案建議遷移至 DateTime 類別,獲得更好的可讀性、時區處理與不可變性保證。記住:時間處理的核心難點在於時區與夏令時間,務必在架構層面統一規範。