萬盛學電腦網

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

PHP 取得指定日期所在月份的第一天與最後一天 (含時分秒)

現代 DateTime 寫法 (推薦)

<?php
function getMonthRange(DateTimeInterface $date, bool $firstDay = true): DateTime {
    $clone = clone $date;
    if ($firstDay) {
        return $clone->modify('first day of this month')->setTime(0, 0, 0);
    } else {
        return $clone->modify('last day of this month')->setTime(23, 59, 59);
    }
}

// 使用
$date = new DateTime('2024-02-15 14:30:00');
echo "月初: " . getMonthRange($date, true)->format('Y-m-d H:i:s') . "\n";  // 2024-02-01 00:00:00
echo "月末: " . getMonthRange($date, false)->format('Y-m-d H:i:s') . "\n"; // 2024-02-29 23:59:59 (閏年)
?>

傳統 date()/strtotime() 寫法

<?php
function getMonthRangeLegacy(string $date, bool $firstDay = true): string {
    $ts = strtotime($date);
    if ($firstDay) {
        return date('Y-m-01 00:00:00', $ts);
    } else {
        $days = (int)date('t', $ts); // 當月天數
        return date("Y-m-{$days} 23:59:59", $ts);
    }
}

echo getMonthRangeLegacy('2024-02-15', true)  . "\n"; // 2024-02-01 00:00:00
echo getMonthRangeLegacy('2024-02-15', false) . "\n"; // 2024-02-29 23:59:59
?>

應用場景:SQL 範圍查詢

<?php
$start = getMonthRange(new DateTime(), true)->format('Y-m-d H:i:s');
$end   = getMonthRange(new DateTime(), false)->format('Y-m-d H:i:s');

$sql = "SELECT * FROM orders
        WHERE created_at BETWEEN ? AND ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$start, $end]);
$orders = $stmt->fetchAll();
?>

注意事項

  • date('t') / modify('last day of this month') 自動處理閏年 (2 月 28/29 天)。
  • 時區一致性:資料庫、PHP、應用層統一使用 UTC 儲存,顯示時轉換使用者時區。
  • 避免使用 strtotime('+1 month') 計算下個月首日,31 號會跑到下下個月。
copyright © 萬盛學電腦網 all rights reserved