/// <summary> /// Returns the count of the occurrences a given DayOfWeek in a /// month of a particular year /// </summary> /// <param name="day"></param> /// <param name="month"></param> /// <param name="year"></param> /// <returns></returns> public static int DayOfWeekCount(DayOfWeek day, int month, int year) { int returnValue = 0; int daysInMonth = DateTime.DaysInMonth(year, month); int extraDays = daysInMonth % 7; DayOfWeek firstDayOfMonth = (new DateTime(year, month, 1)).DayOfWeek; if (extraDays > 0) { if (extraDays == 1 && day == firstDayOfMonth) { returnValue = 5; } else if (extraDays == 2 && (day == firstDayOfMonth || day == (firstDayOfMonth.AddDays(1)))) { returnValue = 5; } else if (extraDays == 3 && (day == firstDayOfMonth || day == (firstDayOfMonth.AddDays(1)) || day == (firstDayOfMonth.AddDays(2)))) { returnValue = 5; } else { returnValue = 4; } } else { // // There are always 4 occurrences // returnValue = 4; } return(returnValue); }
public static IEnumerable <DayOfWeek> GetDaysBetween(this DayOfWeek from, DayOfWeek to, bool includeBoundary = true) { if (includeBoundary) { yield return(from); } if (from != to) { var next = from.AddDays(1); while (next != to) { yield return(next); next = next.AddDays(1); } } if (includeBoundary && from != to) { yield return(to); } }