PHP - easter_date() 函式



PHP 日曆easter_date()函式用於獲取指定年份復活節午夜的 Unix 時間戳。如果年份在 32 位系統上早於 1970 年或晚於 2037 年,或者在 64 位系統上晚於 2,000,000,000 年,則會丟擲 ValueError 異常。

語法

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

int easter_date ( int $year = null, int $mode = CAL_EASTER_DEFAULT )

引數

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

  • $year - 年份必須在 32 位系統上介於 1970 年和 2037 年之間,在 64 位系統上介於 1970 年和 2,000,000,000 年之間。如果未指定或為 null,則預設為本地時間的當前年份。

  • $mode - 可選引數。當選擇 CAL_EASTER_ALWAYS_JULIAN 選項時,可以使用儒略曆計算復活節日期。

返回值

easter_date()函式返回指定年份復活節午夜的 Unix 時間戳。

PHP 版本

easter_date()函式首次引入於 PHP 4 的核心版本中,並在 PHP 5、PHP 7 和 PHP 8 中繼續良好地執行。

示例 1

我們將向您展示 PHP 日曆easter_date()函式的基本示例,以查詢指定年份的復活節日期。

<?php
   // Calculate and display the Easter date for 1995
   echo date("M-d-Y", easter_date(1995)) . "\n"; 
   
   // Calculate and display the Easter date for 2015
   echo date("M-d-Y", easter_date(2015)) . "\n"; 
   
   // Calculate and display the Easter date for 2024
   echo date("M-d-Y", easter_date(2024)) . "\n"; 
?>

輸出

以下是以下程式碼的結果:

Apr-15-1995
Apr-04-2015
Mar-30-2024

示例 2

在下面的 PHP 示例中,我們將使用easter_date()函式計算當前年份的復活節日期,並將其顯示到控制檯。

<?php
   // Calculate the easter date of the current year
   $easter = easter_date();

   // Display the Easter date for 1995
   echo "Easter Date for the current year: ".date("Y-m-d", $easter);
?> 

輸出

這將生成以下輸出:

Easter Date for the current year: 2024-03-31

示例 3

下面的程式碼計算 2023 年的復活節日期。然後,它生成一個新的 DateTime 物件,並將時間戳設定為計算出的復活節日期。最後,它格式化並顯示日期為“月-日-年”。

<?php
   // Calculate the Easter date for 2023
   $timestamp = easter_date(2023);
   
   $datetime = new \DateTime();
   $datetime->setTimestamp($timestamp);
   
   echo $datetime->format('M-d-Y'); 
?> 

輸出

這將生成以下輸出:

Apr-08-2023

示例 4

在下面的示例中,我們將建立一個函式來計算給定年份復活節星期日的準確日期。並使用迴圈和easter_date()函式計算給定年份的復活節日期。

<?php
   // Function to calculate the exact date of Easter Sunday
   function calculateEasterDate($year) {

      // Set the base date to March 21 of the given year
      $march21 = new DateTime("$year-03-21");
   
      // Calculate the number of days
      $daysToAdd = easter_days($year);
   
      // Add the calculated number of days to March 21 
      return $march21->add(new DateInterval("P{$daysToAdd}D"));
   }
   
   // Loop over the years 2012 to 2015
   foreach (range(2020, 2024) as $currentYear) {
      
      // Print the year and the related Easter Sunday date in "Month Day" format
      printf("Easter Date in %d is on %s\n", $currentYear, calculateEasterDate($currentYear)->format('F j'));
   }
?> 

輸出

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

Easter Date in 2020 is on April 12
Easter Date in 2021 is on April 4
Easter Date in 2022 is on April 17
Easter Date in 2023 is on April 9
Easter Date in 2024 is on March 31
php_function_reference.htm
廣告