Code_Steel
Code_Steel

Reputation: 435

How to Calculate the Date when Given Month, DayOfWeek and WeekOfMonth?

I need to calculate holidays which always occur on varying day in a certain week every year. They usually occur on a first weekday in a specific week and month.

I have these properties: Name, Month, DayOfWeek, WeekOfMonth. How do I use DateTime objects to calculate the Day that the holiday falls on?

Upvotes: 1

Views: 173

Answers (1)

Kevin
Kevin

Reputation: 4848

Notice in the code below how they handle Labor Day and Thanksgiving. You'll probably have to do something like this for other holidays that don't always fall on a specific date.

I got this code from U.S. Holiday List in C#

    private static HashSet<DateTime> GetHolidays(int year) 
    { 
        HashSet<DateTime> holidays = new HashSet<DateTime>(); 
        //NEW YEARS 
        DateTime newYearsDate = AdjustForWeekendHoliday(new DateTime(year, 1, 1).Date); 
        holidays.Add(newYearsDate); 
        //MEMORIAL DAY  -- last monday in May 
        DateTime memorialDay = new DateTime(year, 5, 31); 
        DayOfWeek dayOfWeek = memorialDay.DayOfWeek; 
        while (dayOfWeek != DayOfWeek.Monday) 
        { 
            memorialDay = memorialDay.AddDays(-1); 
            dayOfWeek = memorialDay.DayOfWeek; 
        } 
        holidays.Add(memorialDay.Date); 

        //INDEPENCENCE DAY 
        DateTime independenceDay = AdjustForWeekendHoliday(new DateTime(year, 7, 4).Date); 
        holidays.Add(independenceDay); 

        //LABOR DAY -- 1st Monday in September 
        DateTime laborDay = new DateTime(year, 9, 1); 
        dayOfWeek = laborDay.DayOfWeek; 
        while(dayOfWeek != DayOfWeek.Monday) 
        { 
            laborDay = laborDay.AddDays(1); 
            dayOfWeek = laborDay.DayOfWeek; 
        } 
        holidays.Add(laborDay.Date);

        //THANKSGIVING DAY - 4th Thursday in November 
        var thanksgiving = (from day in Enumerable.Range(1, 30) 
                       where new DateTime(year, 11, day).DayOfWeek == DayOfWeek.Thursday 
                       select day).ElementAt(3); 
        DateTime thanksgivingDay = new DateTime(year, 11, thanksgiving); 
        holidays.Add(thanksgivingDay.Date);

        DateTime christmasDay = AdjustForWeekendHoliday(new DateTime(year, 12, 25).Date); 
        holidays.Add(christmasDay); 
        return holidays; 
    }

    public static DateTime AdjustForWeekendHoliday(DateTime holiday) 
    { 
        if (holiday.DayOfWeek == DayOfWeek.Saturday) 
        { 
            return holiday.AddDays(-1); 
        } 
        else if (holiday.DayOfWeek == DayOfWeek.Sunday) 
        { 
            return holiday.AddDays(1); 
        } 
        else 
        { 
            return holiday; 
        } 
    }

Upvotes: 1

Related Questions