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?
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?
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