函式封裝
<?php
/**
* 產生區間日期清單
* @param int $startTs 起始時間戳
* @param int $endTs 結束時間戳
* @return array ['timestamps'=>[], 'dates'=>[], 'weeks'=>[]]
*/
function dateRangeList(int $startTs, int $endTs): array
{
if ($endTs < $startTs) return ['timestamps'=>[], 'dates'=>[], 'weeks'=>[]];
$result = ['timestamps' => [], 'dates' => [], 'weeks' => []];
$oneDay = 86400;
for ($ts = $startTs; $ts <= $endTs; $ts += $oneDay) {
$result['timestamps'][] = $ts;
$result['dates'][] = date('Y年m月d日', $ts);
$result['weeks'][] = ['日','一','二','三','四','五','六'][(int)date('w', $ts)];
}
return $result;
}
// 使用範例
$list = dateRangeList(strtotime('2024-05-01'), strtotime('2024-05-10'));
foreach ($list['dates'] as $i => $date) {
echo "$date (週{$list['weeks'][$i]})\n";
}
進階:支援任意步長與格式
function dateRangeFlexible(
string $start,
string $end,
string $interval = 'P1D',
string $format = 'Y-m-d',
?DateTimeZone $tz = null
): \Generator {
$startDt = new DateTimeImmutable($start, $tz);
$endDt = new DateTimeImmutable($end, $tz);
$intv = new DateInterval($interval);
for ($dt = $startDt; $dt <= $endDt; $dt = $dt->add($intv)) {
yield $dt->format($format) . ' (週' . ['日','一','二','三','四','五','六'][$dt->format('w')] . ')';
}
}
foreach (dateRangeFlexible('2024-05-01', '2024-05-10', 'P2D') as $line) {
echo "$line\n"; // 每隔兩天
}
行事曆 UI 整合建議
- 前端使用
FullCalendar、Day.js 或原生 <input type="date">。
- 後端提供
application/json 介面,前端按月請求區間資料。
- 資料庫查詢以
WHERE date_col BETWEEN ? AND ? 利用索引。