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

PHP 獲取當月最後一天:閏年判斷實作

     編輯:PHP 相關知識

PHP 獲取當月最後一天:閏年判斷實作

取得某月天數是日曆、排程、帳單系統常見需求。本文提供純 PHP 邏輯實作,不依賴 cal_days_in_month() 擴展,適合受限環境。

核心邏輯

  • 2 月:閏年 29 天,平年 28 天。
  • 4、6、9、11 月:30 天。
  • 其餘月份:31 天。

類別封裝實作

<?php
class DateHelper {
    public $year;
    public $month;

    public function __construct($year = null, $month = null) {
        $this->year  = $year  ?? (int)date('Y');
        $this->month = $month ?? (int)date('m');
    }

    public function getLastDay() {
        if ($this->month === 2) {
            return $this->isLeapYear($this->year) ? 29 : 28;
        }
        if (in_array($this->month, [4, 6, 9, 11])) {
            return 30;
        }
        return 31;
    }

    public function isLeapYear($year) {
        // 閏年規則:能被4整除但不能被100整除,或能被400整除
        return (($year % 4 === 0 && $year % 100 !== 0) || $year % 400 === 0);
        // 或直接用 PHP 內建:return (bool)date('L', strtotime("$year-01-01"));
    }
}

// 使用範例
$helper = new DateHelper(2024, 2);
echo $helper->getLastDay(); // 29 (2024 為閏年)

現代 PHP (5.1+) 內建最佳做法

$lastDay = (int)date('t', strtotime('2024-02-01')); // 29
// 或
$lastDay = cal_days_in_month(CAL_GREGORIAN, 2, 2024); // 需 calendar 擴展

應用場景

  • 日期選擇器動態生成日期選項。
  • 月結帳單周期計算 (如每月 1 號至最後一天)。
  • 定時任務判斷月末執行邏輯。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved