Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
}
like image 321
Kevin Avatar asked Nov 13 '08 22:11

Kevin


1 Answers

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.

like image 166
Robert Wagner Avatar answered Oct 06 '22 00:10

Robert Wagner