PHP - cal_days_in_month() 函式



PHP 日曆 cal_days_in_month() 函式用於查詢指定日曆中某年某月的日數。當您想知道一個月有多少天,或者想要驗證日期或處理日曆時,此函式非常有用。

語法

以下是 PHP 日曆 cal_days_in_month() 函式的語法:

int cal_days_in_month (int $calendar, int $month, int $year)

引數

以下是 cal_days_in_month() 函式的引數:

  • $calendar - 使用的日曆。

  • $month - 月份,數字表示,例如 1 代表一月,2 代表二月,等等。

  • $year - 年份,四位數字,例如 2024。

PHP 支援多種日曆型別:

  • CAL_GREGORIAN - 格里高利曆(預設)。

  • CAL_JULIAN - 朱利安歷。

  • CAL_JEWISH - 希伯來曆。

  • CAL_FRENCH - 法國革命歷。

返回值

cal_days_in_month() 函式返回一個整數,表示給定月份和年份的日數,使用給定的日曆計算。

PHP 版本

cal_days_in_month() 函式最早在 PHP 4.1.0 中引入,在 PHP 5、PHP 7 和 PHP 8 中都能輕鬆使用。

示例 1

首先,我們將向您展示 PHP 日曆 cal_days_in_month() 函式的基本示例,以查詢 2024 年 2 月的日數。這裡我們使用 CAL_GREGORIAN 常量來指定日曆。

<?php
   // Calculate the days in the leap year
   $days = cal_days_in_month(CAL_GREGORIAN, 2, 2024);

   // Display the result
   echo "The February month of 2024 has $days days.";
?>

輸出

程式碼計算 2 月的日數,因為 2024 年是閏年,所以它將返回 29 天。以下是以下程式碼的結果:

The February month of 2024 has 29 days.

示例 2

此程式碼將使用 cal_days_in_month() 函式並使用格里高利曆查詢 2023 年 2 月(非閏年)的日數。

<?php
   // Calculate the days in the non-leap year
   $days = cal_days_in_month(CAL_GREGORIAN, 2, 2023);

   // Display the result
   echo "The February month of 2023 has $days days.";
?> 

輸出

上述程式碼檢查非閏年的日數。因此,這將生成以下輸出:

The February month of 2023 has 28 days.

示例 3

此示例使用朱利安歷,使用 cal_days_in_month() 函式查詢 2022 年 3 月的日數。

<?php
   // Calculate the days in the month of Julian calendar
   $days = cal_days_in_month(CAL_JULIAN, 3, 2022);

   // Display the result
   echo "March 2022 (Julian) has $days days.";
?> 

輸出

這將為朱利安歷建立以下輸出:

March 2022 (Julian) has 31 days.

示例 4

在下面的示例中,我們使用 cal_days_in_month() 函式透過使用 CAL_JEWISH 常量來查詢希伯來曆中的日數。

<?php
   // Calculate the days in the month of Jewish calendar
   $days = cal_days_in_month(CAL_JEWISH, 1, 5784);

   // Display the result
   echo "Nisan 5784 (Jewish) has $days days.";
?> 

輸出

以下是上述程式碼的輸出:

Nisan 5784 (Jewish) has 30 days.
php_function_reference.htm
廣告
© . All rights reserved.