Search code examples
c#.netdatecalendar

How do I determine if a given date is the Nth weekday of the month?


Here is what I am trying to do: Given a date, a day of the week, and an integer n, determine whether the date is the nth day of the month.

For example:

  • input of 1/1/2009,Monday,2 would be false because 1/1/2009 is not the second Monday

  • input of 11/13/2008,Thursday,2 would return true because it is the second Thursday

How can I improve this implementation?

private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n)
{
    int d = date.Day;
    return date.DayOfWeek == dow && (d/ 7 == n || (d/ 7 == (n - 1) && d % 7 > 0));
}

Solution

  • You could change the check of the week so the function would read:

    private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){
      int d = date.Day;
      return date.DayOfWeek == dow && (d-1)/7 == (n-1);
    }
    

    Other than that, it looks pretty good and efficient.