public static IEnumerable<int> DaysInMonth(int year, int month, DayOfWeek dow)
{
DateTime monthStart = new DateTime(year, month, 1);
return Enumerable.Range(0, DateTime.DaysInMonth(year, month))
.Select(day => monthStart.AddDays(day))
.Where(date => date.DayOfWeek == dow)
.Select(date => date.Day);
}
Your example:
var wednesdaysInSeptember2015 = DaysInMonth(2015, 9, DayOfWeek.Wednesday);
Console.Write(String.Join(",", wednesdaysInSeptember2015)); // 2,9,16,23,30
For what it’s worth, here is a performance optimized version:
public static IEnumerable<int> DaysInMonthMicroOptimized(int year, int month, DayOfWeek dayOfWeek)
{
DateTime monthStart = new DateTime(year, month, 1);
int distanceToDayOfWeek = (dayOfWeek < monthStart.DayOfWeek ? 7 : 0) + dayOfWeek - monthStart.DayOfWeek;
DateTime dayOfWeekInMonth = monthStart.AddDays(distanceToDayOfWeek);
yield return dayOfWeekInMonth.Day;
while((dayOfWeekInMonth = dayOfWeekInMonth.AddDays(7)).Month == month)
yield return dayOfWeekInMonth.Day;
}
3
solved How to get the day number in a month in c# [closed]