How to find the 3rd Friday in a month with C#?

后端 未结 19 1037
野的像风
野的像风 2020-11-27 06:07

Given a date (of type DateTime), how do I find the 3rd Friday in the month of that date?

19条回答
  •  感动是毒
    2020-11-27 06:38

    This is a version that uses LINQ and functional programming style.

    It works like this.

    First, take all of the days of the month. Then select only the ones of the right day (Friday). Finally take the nth (3rd) entry and return.

    // dt: The date to start from (usually DateTime.Now)
    // n: The nth occurance (3rd)
    // weekday: the day of the week to look for
        public DateTime GetNthWeekdayOfMonth(DateTime dt, int n, DayOfWeek weekday)
        {
            var days = Enumerable.Range(1, DateTime.DaysInMonth(dt.Year, dt.Month)).Select(day => new DateTime(dt.Year, dt.Month, day));
    
            var weekdays = from day in days
                                where day.DayOfWeek == weekday
                                orderby day.Day ascending
                                select day;
    
            int index = n - 1;
    
            if (index >= 0 && index < weekdays.Count())
                return weekdays.ElementAt(index);
    
            else
                throw new InvalidOperationException("The specified day does not exist in this month!");
       }
    

提交回复
热议问题