報表統計、帳單週期、排程任務常需「某日期所在月份的第一天/最後一天」或「所在週的起止日期」。本文封裝三個實用函式,涵蓋月、週、任意月份偏移,直接可用。
<?php
/**
* 取得指定日期所在月份的第一天與最後一天
* @param string $date 任意合法日期字串,如 '2024-03-15'、'2024/03/15'、'now'
* @return array [firstDay, lastDay] 格式 Y-m-d
*/
function getMonthRange(string $date): array
{
$ts = strtotime($date);
if ($ts === false) throw new InvalidArgumentException('Invalid date');
$first = date('Y-m-01', $ts);
$last = date('Y-m-t', $ts); // t = 月份天數
return [$first, $last];
}
// 用法
[$start, $end] = getMonthRange('2024-02-10'); // ['2024-02-01', '2024-02-29']
?>
<?php
/**
* 取得指定日期所在週的起止日期
* @param string $date
* @param int $weekStart 0=週日, 1=週一 (ISO-8601)
* @return array [weekStart, weekEnd] Y-m-d
*/
function getWeekRange(string $date, int $weekStart = 1): array
{
$ts = strtotime($date);
if ($ts === false) throw new InvalidArgumentException('Invalid date');
$w = (int)date('w', $ts); // 0=週日..6=週六
$diff = ($w - $weekStart + 7) % 7; // 距離本週起始日天數
$startTs = $ts - $diff * 86400;
$endTs = $startTs + 6 * 86400;
return [date('Y-m-d', $startTs), date('Y-m-d', $endTs)];
}
// 用法
[$ws, $we] = getWeekRange('2024-03-15', 1); // 週一起 ['2024-03-11', '2024-03-17']
[$ws, $we] = getWeekRange('2024-03-15', 0); // 週日起 ['2024-03-10', '2024-03-16']
?>
<?php
/**
* 取得指定日期偏移 $step 月後的月份範圍
* @param string $date 基準日期
* @param int $step 月份偏移 (0=本月, 1=下月, -1=上月...)
* @return array ['range'=>[first,last], 'days'=>[每一天 Y-m-d]]
*/
function getMonthRangeWithOffset(string $date, int $step = 0): array
{
$base = strtotime($date . ' first day of ' . ($step >= 0 ? '+' : '') . abs($step) . ' months');
if ($base === false) throw new InvalidArgumentException('Invalid date');
$first = date('Y-m-01', $base);
$last = date('Y-m-t', $base);
$days = [];
$cur = strtotime($first);
while (date('Y-m', $cur) === date('Y-m', $base)) {
$days[] = date('Y-m-d', $cur);
$cur += 86400;
}
return ['range' => [$first, $last], 'days' => $days];
}
// 用法
$r = getMonthRangeWithOffset('2024-01-15', 2); // 往後兩個月
// $r['range'] => ['2024-03-01', '2024-03-31']
// $r['days'] => ['2024-03-01', ..., '2024-03-31']
?>
<?php
function getMonthRangeModern(string $date): array
{
$dt = new DateTimeImmutable($date);
$first = $dt->modify('first day of this month');
$last = $dt->modify('last day of this month');
return [$first->format('Y-m-d'), $last->format('Y-m-d')];
}
?>
DateTimeImmutable 避免副作用、支援時區、閏秒處理更健壯,新專案優先採用。
strtotime('+1 month') 在 1/31 會跳到 3/3(因 2 月無 31 號),改用 'first day of +1 month' 更穩定。將以上函式放入共用工具類或 Helper,即可在專案任處複用,乾淨又可靠。