I want to be able to calculate when the next Mother's day will be in PHP but I'm not sure how to do this as in the UK it is based on lent and Easter which is changes every year. Thanks :)
CodePudding user response:
Well, this is an interesting one. From what I see, Mother's Day in the UK falls on the 3rd Sunday before Easter. PHP has a function called easter_date, that gives us the timestamp of Easter in a given year. So what you have to do is get the Easter timestamp, then use strtotime to subtract 3 weeks.
$easter = easter_date(2021); // 1617508800
$easter_date = date('Y-m-d', $easter); // "2021-04-04"
$mothers_day = date('Y-m-d', strtotime($easter_date).' -3 weeks')); // 2021-03-14
Or in a one-liner:
$mothers_day = date('Y-m-d', strtotime(date('Y-m-d', easter_date(2021)).' -3 weeks'));
Edit Apparently this only works until 2037. There is another function, easter_days, which calculates the number days Easter falls after March 21st. In that case, you can do this:
$year = 2058;
$mothers_day = date('Y-m-d', strtotime("$year-3-21 ".easter_days($year). " days -3 weeks")); // 2058-03-24
CodePudding user response:
The function easter_date is only valid for years between 1970 and 2037. Better use the function easter_days and DateTime.
function createDateEastern($year, $timezone = null) {
$easterDays = easter_days($year, CAL_EASTER_ALWAYS_GREGORIAN);
return date_create($year.'-3-21',$timezone)->modify($easterDays.' Days');
}
You can easily calculate the UK Mothers Day with
$motheringSunday = createDateEastern(2021)->modify('-3 weeks');
//object(DateTime)#2 (3) { ["date"]=> string(26) "2021-03-14 00:00:00.000000"
You can also use the DateTime extension dt. This class can execute chains with date expressions especially for such holiday calculations. As an example, Mother's Day in the current year:
$dt = dt::create('{{easter}}|-3 Weeks');
echo $dt->format('Y-m-d'); //2021-03-14