Calculating the location of Easter in C#
Posted: (EET/GMT+2)
Just recently, I had the need to implement a calendar application with .NET that was able calculate the location of Easter (in the way the Western church sees it).
Since the location of Easter depends on the Moon calendar, calculating its location each year isn't trivial. Nonetheless, a calculation routine has already been written for C#, and I'm showing here a slightly more readable version of the code:
public static DateTime GetEasterSunday(int year)
{
// check that the input year is within range
if ((year < 1900) || (year > 2100))
{
throw new ArgumentOutOfRangeException("year",
"The year must be between 1900 and 2100 inclusive.");
}
// calculate Easter
int golden = year % 19; // the "golden" lunar cycle
int century = year / 100;
int h = (century - (century / 4) - ((8 * century + 13) / 25) + 19 * golden + 15) % 30;
int i = h - (h / 28) * (1 - (h / 28) * (29 / (h + 1)) * (21 - golden) / 11);
// convert to day and month
int day = i - ((year + (year / 4) +i + 2 - century + (century / 4)) % 7) + 28;
int month = 3;
// does the day overlap?
if (day > 31)
{
month++;
day -= 31;
}
// convert the result to a DateTime
DateTime easterSunday = new DateTime(year, month, day);
return easterSunday;
}
This calculation is based on the so-called Butcher's Method.
Using this routine is simple: just call the method and pass in the year. You will receive back a DateTime giving the date of the Easter Sunday for that particular year.
Hope this helps!