0

I need the current Easter date this year in my code. Easter 2021 this year will be observed on Sunday, April 4.

But when I run echo date('Y-m-d',easter_date(2021)); PHP returns:

2021-04-03

How is that possible? What's wrong?

angelique000
  • 899
  • 3
  • 10
  • 28
  • 1
    It does return the correct date, but you probably didnt set your correct timezone. [date_default_timezone_set](https://www.php.net/manual/en/function.date-default-timezone-set.php) – Definitely not Rafal Jan 28 '21 at 11:29

2 Answers2

2

Taken from the PHP Manual: Link

Note: easter_date() relies on your system's C library time functions, rather than using PHP's internal date and time functions. As a consequence, easter_date() uses the TZ environment variable to determine the time zone it should operate in, rather than using PHP's default time zone, which may result in unexpected behaviour when using this function in conjunction with other date functions in PHP.

As a workaround, you can use the easter_days() with DateTime and DateInterval to calculate the start of Easter in your PHP time zone as follows:

<?php
function get_easter_datetime($year) {
    $base = new DateTime("$year-03-21");
    $days = easter_days($year);

    return $base->add(new DateInterval("P{$days}D"));
}

foreach (range(2015, 2022) as $year) {

    printf("Easter in %d is on %s\n",
           $year,
           get_easter_datetime($year)->format('D F j'));
}

RESULTS

PHP 8.0.1
Easter in 2015 is on Sun April 5
Easter in 2016 is on Sun March 27
Easter in 2017 is on Sun April 16
Easter in 2018 is on Sun April 1
Easter in 2019 is on Sun April 21
Easter in 2020 is on Sun April 12
Easter in 2021 is on Sun April 4
Easter in 2022 is on Sun April 17
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Excellent workaround. How can I get Sunday, April 5th format? – CodeForGood Mar 28 '21 at 09:17
  • 1
    `get_easter_datetime($year)->format('l, F jS')` [See how to format dates and times in this page of the manual](https://www.php.net/manual/en/datetime.format.php) – RiggsFolly Mar 28 '21 at 13:20
0

A more flexible approach would be to use the Easter method.

echo dt::Easter(2021)->format('l, j F Y');
//Sunday,4 April 2021

//Orthodox Easter 2021
echo dt::Easter(2021,dt::EASTER_EAST)->format('l, j F Y'); 
//Sunday, 2 May 2021

The method Easter is part of this PHP class.

jspit
  • 7,276
  • 1
  • 9
  • 17