$days = [];
for ($i = 0; $i <= 30; $i++) {
$days[] = date('Y-m-d', strtotime("-$i days"));
}
print_r($days);
輸出:['2024-05-20', '2024-05-19', ..., '2024-04-20'](含今天共 31 筆)。
| 需求 | strtotime 參數 | 範例 |
|---|---|---|
| 前 30 天(不含今天) | -1 day ~ -30 days | for($i=1;$i<=30;$i++) strtotime("-$i days") |
| 未來 7 天 | +$i days | for($i=1;$i<=7;$i++) strtotime("+$i days") |
| 本週一至週日 | monday this week ~ sunday this week | strtotime('monday this week') |
| 上個月第一天 | first day of last month | date('Y-m-d', strtotime('first day of last month')) |
$today = new DateTimeImmutable();
$period = new DatePeriod(
$today->sub(new DateInterval('P30D')), // 30 天前
new DateInterval('P1D'), // 間隔 1 天
31, // 含今天共 31 個
DatePeriod::EXCLUDE_START_DATE
);
$days = iterator_to_array($period);
array_walk($days, fn(&$d) => $d = $d->format('Y-m-d'));
print_r($days);
優點:不可變物件、時區支援完整、鏈式呼叫、型別安全。
date_default_timezone_set('Asia/Taipei'); // 腳本開頭統一設定
// 或
$dt = new DateTimeImmutable('now', new DateTimeZone('Asia/Taipei'));
未設定時區會產生 E_WARNING 並預設 UTC,導致日期偏移。