Finding Thanksgiving Date in C#

I was looking for a way to determine the day of Thanksgiving for the current year. Looked online, but did not find a solution that worked. Thus had to come up with my own code for this problem.

Unlike some holidays, Thanksgiving moves around from year to year because it is based on a day of the week (in this case the 4th Thursday of November) instead of a specific date each year.

private DateTime GetThanksgivingDate()
{
    DateTime testDate = DateTime.Now;

    for (int i = 22; i <= 30; i++)
    {
        testDate = new DateTime(DateTime.Now.Year, 11, i, 0, 0, 0);
        if (testDate.DayOfWeek != DayOfWeek.Thursday)
        {
            continue;
        }
    }

    return testDate;
}

To explain the code above, get the current date first and use it as a test date. To simplify the process, we know that Thanksgiving cannot be before November 22nd and obviously cannot be after November 30th (cause it only has 30 days in the month).

Thus the for loop checks each one of those days and the first one that it finds that is a Thursday, and then exits the loop and returns that date back to the caller.

While this code is specific for Thanksgiving Day, it can be adapted to other holidays that are month and week based like President's Day (3rd Monday in February), Memorial Day (last Monday in May), and Labor Day (first Monday in September).

Hopefully this code helps someone with their project!

Posted: 2022-06-19
Author: Kenny Robinson, @almostengr