首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 獲取指定月份首尾時間戳:一行代碼搞定,拒絕繁瑣計算

     編輯:PHP 相關知識

PHP 獲取指定月份首尾時間戳:一行代碼搞定,拒絕繁瑣計算

網上流傳的「獲取月首尾時間戳」函數多顯冗長。實際上,利用 PHP 內置日期函數的相對時間特性,可極簡實現。本文提供現代寫法(PHP 5.3+)與兼容寫法兩個版本。

推薦:現代簡潔版(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
)
*/

兼容版(PHP 5.2 或不支持相對時間語法環境)

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];
}

核心原理解析

  1. 月首:固定為「年-月-01 00:00:00」,直接 strtotime 解析。
  2. 月尾:利用 strtotime("+1 month", $start) 獲取「下月 1 號 00:00:00」,再 減 1 秒 即得「當月最後一天 23:59:59」。
  3. 自動處理大小月、閏年,無需手動判斷 28/29/30/31 天。

進階用法:直接獲取 DateTime 對象(推薦現代項目)

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 時會導致月份溢出。本文方案通用且無邊界問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved