萬盛學電腦網

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

PHP 計算指定月份首尾日期的多種方法與效能比較

前言

取得某月第一天(00:00:00)與最後一天(23:59:59)是報表統計、帳單週期、行程安排等常見需求。PHP 提供多種實作方式,本文比較 strtotime()、DateTime、DateTimeImmutable 的寫法、可讀性與效能。

方法一:strtotime() 相對日期格式(經典、簡潔)

<?php
$today = '2024-12-15'; // 或 date('Y-m-d')

// 本月第一天 00:00:00
$firstDay = date('Y-m-01', strtotime($today));
// 或
$firstDay = date('Y-m-d', strtotime('first day of this month', strtotime($today)));

// 本月最後一天 23:59:59
$lastDay = date('Y-m-t', strtotime($today)); // t = 本月總天數
// 或相對格式
$lastDay = date('Y-m-d', strtotime('last day of this month', strtotime($today)));

// 完整日期時間範圍(常用於 SQL BETWEEN)
$start = date('Y-m-01 00:00:00', strtotime($today));
$end   = date('Y-m-t 23:59:59', strtotime($today));

echo "開始: $start\n結束: $end";
?>

優點:一行搞定、相對格式語意清晰(first day of、last day of)。
缺點:strtotime() 解析字串有開銷,大量循環效能較差;32 位系統 2038 年問題。

方法二:DateTime 物件導向(推薦、功能豐富)

<?php
$date = new DateTime('2024-12-15'); // 或 new DateTime() 當前時間
// $date = new DateTime('2024-12-15', new DateTimeZone('Asia/Taipei')); // 指定時區

// 第一天 00:00:00
$firstDay = clone $date;
$firstDay->modify('first day of this month')->setTime(0, 0, 0);

// 最後一天 23:59:59
$lastDay = clone $date;
$lastDay->modify('last day of this month')->setTime(23, 59, 59);

// 格式化輸出
echo "開始: " . $firstDay->format('Y-m-d H:i:s') . "\n";
echo "結束: " . $lastDay->format('Y-m-d H:i:s') . "\n";

// 直接取得格式化字串
$start = (clone $date)->modify('first day of this month')->format('Y-m-d 00:00:00');
$end   = (clone $date)->modify('last day of this month')->format('Y-m-d 23:59:59');
?>

方法三:DateTimeImmutable(不可變、鏈式呼叫、線程安全)

<?php
$date = new DateTimeImmutable('2024-12-15');

// 鏈式呼叫,無需 clone
$firstDay = $date->modify('first day of this month')->setTime(0, 0, 0);
$lastDay  = $date->modify('last day of this month')->setTime(23, 59, 59);

echo $firstDay->format('Y-m-d H:i:s') . "\n";
echo $lastDay->format('Y-m-d H:i:s') . "\n";

// 取得月份天數
$daysInMonth = (int)$date->format('t'); // 31
?>

方法四:純運算(最高效能、無函數呼叫開銷)

<?php
function getMonthRange(int $year, int $month): array {
    // 驗證月份
    if ($month < 1 || $month > 12) throw new InvalidArgumentException('Invalid month');
    
    // 第一天
    $firstDay = sprintf('%04d-%02d-01 00:00:00', $year, $month);
    
    // 最後一天:下月第一天減 1 秒
    $nextMonth = $month === 12 ? 1 : $month + 1;
    $nextYear  = $month === 12 ? $year + 1 : $year;
    $lastDay = sprintf('%04d-%02d-%02d 23:59:59', $year, $month, 
        (int)date('t', mktime(0, 0, 0, $month, 1, $year)) // 取得當月天數
    );
    
    return ['start' => $firstDay, 'end' => $lastDay];
}

// 使用
$range = getMonthRange(2024, 2); // 閏年 2 月
print_r($range);
// Array ( [start] => 2024-02-01 00:00:00 [end] => 2024-02-29 23:59:59 )
?>

效能比較測試(100萬次循環)

<?php
$iterations = 1_000_000;
$dateStr = '2024-12-15';

// strtotime 版
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
    $s = date('Y-m-01', strtotime($dateStr));
    $e = date('Y-m-t', strtotime($dateStr));
}
echo "strtotime: " . (microtime(true) - $start) . "s\n";

// DateTime 版
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
    $dt = new DateTime($dateStr);
    $s = (clone $dt)->modify('first day of this month')->format('Y-m-d');
    $e = (clone $dt)->modify('last day of this month')->format('Y-m-d');
}
echo "DateTime: " . (microtime(true) - $start) . "s\n";

// DateTimeImmutable 版
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
    $dt = new DateTimeImmutable($dateStr);
    $s = $dt->modify('first day of this month')->format('Y-m-d');
    $e = $dt->modify('last day of this month')->format('Y-m-d');
}
echo "DateTimeImmutable: " . (microtime(true) - $start) . "s\n";

// 純運算版
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
    $s = sprintf('%04d-%02d-01', 2024, 12);
    $e = sprintf('%04d-%02d-%02d', 2024, 12, date('t', mktime(0,0,0,12,1,2024)));
}
echo "純運算: " . (microtime(true) - $start) . "s\n";

/*
典型結果(PHP 8.2):
strtotime: ~1.8s
DateTime: ~2.5s
DateTimeImmutable: ~2.3s
純運算: ~0.6s
*/
?>

時區陷阱與最佳實踐

<?php
// 必須設定預設時區,否則 strtotime/DateTime 使用系統時區(通常 UTC)
date_default_timezone_set('Asia/Taipei');

// 或在 DateTime 建構時指定
$date = new DateTime('2024-12-15', new DateTimeZone('Asia/Taipei'));

// 取得當月範圍(含時區資訊)
$start = (new DateTimeImmutable('first day of this month', new DateTimeZone('Asia/Taipei')))
    ->setTime(0, 0, 0);
$end = (new DateTimeImmutable('last day of this month', new DateTimeZone('Asia/Taipei')))
    ->setTime(23, 59, 59);

// SQL 查詢範例(MySQL)
$sql = "SELECT * FROM orders WHERE created_at BETWEEN ? AND ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')]);
?>

結語

根據場景選擇:

  • 簡單腳本、低頻呼叫:strtotime('first day of this month') 最簡潔語意化
  • 現代專案、需時區處理、不可變性:DateTimeImmutable 首選
  • 高頻循環、效能敏感:純運算或預先計算快取
  • 資料庫查詢:輸出 Y-m-d H:i:s 格式,搭配參數綁定

核心原則:統一使用 UTC 儲存,顯示時轉換為用戶時區,避免時區導致的日期邊界偏移。

copyright © 萬盛學電腦網 all rights reserved