請記住,如果您只想知道目前月份的天數,請使用 date 函式
$days = date("t");
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
cal_days_in_month — 傳回指定年份和日曆中,某月份的天數
calendar
用於計算的日曆
month
所選日曆中的月份
year
所選日曆中的年份
指定日曆中,所選月份的天數長度
範例 #1 cal_days_in_month() 範例
<?php
$number = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "2003 年 8 月有 {$number} 天";
?>
這是我剛寫的一個單行函式,用於找出月份的天數,而且不依賴任何其他函式。
我這樣做的原因是,我剛發現我忘記編譯 PHP 以支援日曆,而我為我網站的開放原始碼部分編寫的類別被破壞了。因此,與其重新編譯 PHP(我想我明天會處理),我只是編寫了這個函式,它應該一樣有效,並且始終可以在沒有 PHP 日曆擴充功能或任何其他 PHP 函式的情況下運作。
我用舊的指關節和指關節之間的方法來學習月份的天數,這應該可以解釋 mod 7 的部分。:)
<?php
/*
* days_in_month($month, $year)
* 傳回指定月份和年份的天數,並考量閏年。
*
* $month:數字月份 (整數 1-12)
* $year:數字年份 (任何整數)
*
* Prec: $month 是介於 1 和 12 之間的整數(包含 1 和 12),而 $year 是一個整數。
* Post: 無
*/
// 由 ben at sparkyb dot net 修正
function days_in_month($month, $year)
{
// 計算一個月中的天數
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
?>
盡情享用,
David Bindel
function lastDayOfMonth(string $time, int $deltaMonth, string $format = 'Y-m-d')
{
try {
$year = date('Y', strtotime($time));
$month = date('m', strtotime($time));
$increaYear = floor(($deltaMonth + $month - 1) / 12);
$year += $increaYear;
$month = (($deltaMonth + $month) % 12) ?: 12;
$day = cal_days_in_month(CAL_GREGORIAN, $month, $year);
return $time . ' + ' . $deltaMonth . ' => ' . date($format, strtotime($year . '-' . $month . '-' . $day)) . "\n";
} catch (Exception $e) {
throw $e;
}
}