Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Finding Out Which Monday Is The 3rd Monday Of The Month?

If I'm writing some C# code that runs through a year of dates (iterating by day) and want something special to happen every 3rd Monday of the month, how can I accomplish this?

In other words, what is the best way to find which Monday of the month a current Monday is?

like image 377
sooprise Avatar asked May 13 '10 14:05

sooprise


2 Answers

public bool IsThirdMondayOfMonth(DateTime dt)
{
  if(dt.DayOfWeek == DayOfWeek.Monday && dt.Day > 14 && dt.Day <= 21)
  {
    return true;
  }
  return false;
}
like image 100
sechastain Avatar answered Sep 30 '22 00:09

sechastain


I don't think your "in other words" really restates the problem that you describe first, so I'll answer both.

Here's a fairly simple method that will determine the nth occurrence of a particular day of the week in a given month in a given year.

public static DateTime DayOccurrence(int year, int month, DayOfWeek day, 
    int occurrenceNumber)
{
    DateTime start = new DateTime(year, month, 1);
    DateTime first = start.AddDays((7 - ((int)start.DayOfWeek - (int)day)) % 7);

    return first.AddDays(7 * (occurrenceNumber - 1));
}

Determining which Monday (or any other day) of the month a date is is much easier; just take the ceiling of the day of the month / 7:

public static int DayOccurrence(DateTime date)
{
    return (int)Math.Ceiling(date.Day / 7.0);
}
like image 30
Adam Robinson Avatar answered Sep 30 '22 01:09

Adam Robinson