There is no need to run a loop for this:
private static DateTime GetLastWeekdayOfMonth(DateTime date, DayOfWeek day)
{
DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, 1)
.AddMonths(1).AddDays(-1);
int wantedDay = (int)day;
int lastDay = (int)lastDayOfMonth.DayOfWeek;
return lastDayOfMonth.AddDays(
lastDay >= wantedDay ? wantedDay - lastDay : wantedDay - lastDay - 7);
}
This can be easily converted to an extension method, for example:
public static class DateTimeExtensions
{
public static DateTime GetLastWeekdayOfMonth(this DateTime date, DayOfWeek day)
{
DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, 1)
.AddMonths(1).AddDays(-1);
int wantedDay = (int)day;
int lastDay = (int)lastDayOfMonth.DayOfWeek;
return lastDayOfMonth.AddDays(
lastDay >= wantedDay ? wantedDay - lastDay : wantedDay - lastDay - 7);
}
}
... and then can be used directly from any DateTime object:
DayOfWeek lastSunday = DateTime.Now.GetLastWeekdayOfMonth(DayOfWeek.Sunday);
Update: Bug fixed.
source
share