萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 獲取上個月最後一天:strtotime 相對時間格式最佳實踐

核心方法:strtotime 相對格式

PHP strtotime() 支援強大的自然語言相對時間,獲取上月最後一天極其簡單:

方法一:last day of last month(最語義化)

date_default_timezone_set('PRC'); // 設置時區
echo date('Y-m-d', strtotime('last day of last month')); // 2024-11-30

方法二:first day of this month - 1 day

echo date('Y-m-d', strtotime('first day of this month -1 day'));

方法三:傳統計算法(不推薦)

// 利用當前日期倒推
$day = (int)date('d');
echo date('Y-m-d', strtotime("-$day days")); // 有閏年/月末邊界風險

完整示例代碼

<?php
date_default_timezone_set("PRC");

// 推薦:語義清晰、自動處理閏年/月長差異
$lastDayPrevMonth = date('Y-m-d', strtotime('last day of last month'));
echo "上月最後一天: $lastDayPrevMonth
"; // 獲取上月第一天 $firstDayPrevMonth = date('Y-m-d', strtotime('first day of last month')); echo "上月第一天: $firstDayPrevMonth
"; // 獲取上月天數 $daysInPrevMonth = date('t', strtotime('last month')); echo "上月天數: $daysInPrevMonth
"; // 格式化輸出 echo "上月範圍: $firstDayPrevMonth 至 $lastDayPrevMonth";

strtotime 相對時間速查表

表達式含義示例輸出
last day of last month上月最後一天2024-11-30
first day of last month上月第一天2024-11-01
last day of this month本月最後一天2024-12-31
first day of this month本月第一天2024-12-01
last day of +2 months兩個月後最後一天2025-02-28
last day of -1 month上月最後一天(同義)2024-11-30

時區陷阱與最佳實踐

  1. 必須設置時區: date_default_timezone_set('PRC') 或 php.ini date.timezone,否則用 UTC 導致日期偏移
  2. 避免手動計算天數: 2月/閏年/大小月邊界極易出錯
  3. 業務邏輯用 DateTime: 面向對象、鏈式調用、不可變對象(PHP 5.5+)

DateTime 現代寫法

$dt = new DateTime('last day of last month', new DateTimeZone('PRC'));
echo $dt->format('Y-m-d'); // 2024-11-30

// 區間迭代
$start = new DateTime('first day of last month');
$end   = new DateTime('last day of last month');
$period = new DatePeriod($start, new DateInterval('P1D'), $end);
foreach ($period as $day) {
    echo $day->format('Y-m-d') . "\n";
}

總結

首選 strtotime('last day of last month'):語義明確、自動處理所有日曆邊界、代碼可讀性最強。配合 DateTime 類應對複雜日期運算,徹底告別手動天數計算的坑。

copyright © 萬盛學電腦網 all rights reserved