基本用法
<?php
function getPastDays(int $days = 30): array {
$list = [];
for ($i = 0; $i < $days; $i++) {
$list[] = date('Y-m-d', strtotime("-$i days"));
}
return $list;
}
print_r(getPastDays(7));
/*
Array
(
[0] => 2024-01-15
[1] => 2024-01-14
[2] => 2024-01-13
[3] => 2024-01-12
[4] => 2024-01-11
[5] => 2024-01-10
[6] => 2024-01-09
)
*/
DateTime 物件導向寫法 (推薦 PHP 5.3+)
function getPastDaysOO(int $days = 30): array {
$list = [];
$dt = new DateTime(); // 現在
for ($i = 0; $i < $days; $i++) {
$list[] = $dt->format('Y-m-d');
$dt->modify('-1 day');
}
return $list;
}
// 或使用 DatePeriod (更優雅)
function getPastDaysPeriod(int $days = 30): array {
$end = new DateTime();
$start = (clone $end)->modify("-$days days");
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
$list = [];
foreach ($period as $dt) {
$list[] = $dt->format('Y-m-d');
}
return $list;
}
常見日期格式化參數
| 格式 | 輸出範例 | 說明 |
Y-m-d | 2024-01-15 | ISO 日期 |
Y/m/d | 2024/01/15 | 斜線分隔 |
m/d/Y | 01/15/2024 | 美式慣例 |
Y年m月d日 | 2024年01月15日 | 中文顯示 |
D, d M Y | Mon, 15 Jan 2024 | RFC 2822 |
c | 2024-01-15T00:00:00+08:00 | ISO 8601 |
進階:排除週末 / 只取工作日
function getWorkDays(int $days = 30): array {
$list = [];
$dt = new DateTime();
while (count($list) < $days) {
$dt->modify('-1 day');
$w = (int)$dt->format('N'); // 1=週一 ... 7=週日
if ($w < 6) $list[] = $dt->format('Y-m-d');
}
return $list;
}
效能比較 (10000 次呼叫)
| 方法 | 耗時 | 備註 |
| strtotime() 迴圈 | ~45ms | 字串解析開銷 |
| DateTime::modify() | ~38ms | 物件導向 |
| DatePeriod | ~32ms | 內部優化、最推薦 |
| 手算時間戳 (-86400) | ~12ms | 最快但需自行處理閏秒/夏令 |
時區陷阱
// 確保正確時區
date_default_timezone_set('Asia/Taipei');
// 或
$dt = new DateTime('now', new DateTimeZone('Asia/Taipei'));