Calculating the date of Easter with PHP.

This is a short PHP tutorial on how to calculate what date Easter falls on for a given year. We will achieve this by using PHP’s inbuilt easter_days function.

Unfortunately for us coders, this is one of those weird dates that can change each year, as it was decided that it must fall on the first Sunday after the first ecclesiastical full moon (the Equinox).

However, this post isn’t about the history of Christianity or the Catholic Church, so let’s skip that part and jump straight into the code.

In the code below, I have created a custom function called getEasterDate:

By default, this function above will calculate the date of Easter Sunday for the current year. However, you can also pass in a specific year if needs be.

How this function works.

A quick explanation of how the getEasterDate function works:

  1. We check to see if a specific year was passed in as a parameter. If not, then our code defaults to the current year.
  2. We then use PHP’s easter_days function. This function returns “the number of days after March 21 on which Easter falls for a given year.” March 21st is assumed to be “The Equinox”, by the way.
  3. Finally, we added those days onto the 21st of March and returned the Easter date in a YYYY-MM-DD format.

Below, I’ve written a few examples of this function being used with various years:

As you can see, it’s pretty straight-forward to use.

Why not use the easter_date function?

Some of you are probably wondering why I created a custom function instead of using PHP’s easter_date function. Well, the problem with easter_date is that it does not use PHP’s time zone. Instead, it uses your system’s TZ environment variable.

This can cause unexpected issues if PHP is using a different timezone than the server it is hosted on. Therefore, I would recommend that you manually calculate the date like we did above.

Facebook Comments