網上流傳的「獲取月首尾時間戳」函數多顯冗長。實際上,利用 PHP 內置日期函數的相對時間特性,可極簡實現。本文提供現代寫法(PHP 5.3+)與兼容寫法兩個版本。
<?php
/**
* 獲取指定月份的起始/結束時間戳(含時分秒)
* @param int $year 年份,默認當前年
* @param int $month 月份,默認當前月
* @return array ['start' => int, 'end' => int]
*/
function getMonthRange($year = null, $month = null) {
$year = $year ?? (int)date('Y');
$month = $month ?? (int)date('m');
// 月首:當月 1 號 00:00:00
$start = strtotime("{$year}-{$month}-01 00:00:00");
// 月尾:下月 1 號 00:00:00 減 1 秒 = 當月最後一天 23:59:59
$end = strtotime("+1 month", $start) - 1;
return ['start' => $start, 'end' => $end];
}
// 使用示例
print_r(getMonthRange(2024, 2)); // 2024 年 2 月(閏年)
/* 輸出:
Array
(
[start] => 1706716800 // 2024-02-01 00:00:00
[end] => 1709222399 // 2024-02-29 23:59:59
)
*/
function getMonthRangeCompat($year = '', $month = '') {
$year = $year ?: date('Y');
$month = sprintf('%02d', $month ?: date('m'));
$firstDay = strtotime("{$year}{$month}01000000");
$lastDay = strtotime(date('Y-m-d 23:59:59', strtotime("+1 month -1 day", $firstDay)));
return ['firstday' => $firstDay, 'lastday' => $lastDay];
}
strtotime 解析。strtotime("+1 month", $start) 獲取「下月 1 號 00:00:00」,再 減 1 秒 即得「當月最後一天 23:59:59」。function getMonthRangeDateTime($year = null, $month = null) {
$year = $year ?? (int)date('Y');
$month = $month ?? (int)date('m');
$start = new DateTime("first day of {$year}-{$month} 00:00:00");
$end = (clone $start)->modify('last day of this month 23:59:59');
return ['start' => $start, 'end' => $end];
}
// 直接格式化輸出
$range = getMonthRangeDateTime(2024, 2);
echo $range['start']->format('Y-m-d H:i:s'); // 2024-02-01 00:00:00
echo $range['end']->format('Y-m-d H:i:s'); // 2024-02-29 23:59:59
避坑提醒:舊版代碼常用
mktime(0,0,0,$month+1,0,$year)取月尾,但$month=12時會導致月份溢出。本文方案通用且無邊界問題。