6

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?

sooprise
  • 22,657
  • 67
  • 188
  • 276

4 Answers4

13
public bool IsThirdMondayOfMonth(DateTime dt)
{
  if(dt.DayOfWeek == DayOfWeek.Monday && dt.Day > 14 && dt.Day <= 21)
  {
    return true;
  }
  return false;
}
sechastain
  • 656
  • 3
  • 5
  • 4
    Better: `return (dt.DayOfWeek == DayOfWeek.Monday && dt.Day > 14 && dt.Day < 22);` – Josh Stodola May 13 '10 at 14:53
  • You might want this to be an extension for DateTime. You'll probably come across a number of things like this that are worth keeping in an extension library. – Carlos May 13 '10 at 14:55
  • Alrighty, I was hoping that there was something built in, but didn't think it was too likely. I guess I'll have to take some of these code snippets here. Thanks guys :) – sooprise May 13 '10 at 14:55
9

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);
}
Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
1

Find the Monday that is between the 15th and the 21st, inclusive.

Toby
  • 7,354
  • 3
  • 25
  • 26
0

I don't know if there is a date manipulation library to do what you want, but you can write your own functions pretty easily:

using System;

class Program {
    static void Main(string[] args) {
        int year = 2010;
        int month = 05;
        DateTime thirdMonday = ThirdMonday(year, month);
    }

    private static DateTime ThirdMonday(int year, int month) {
        for (int day = 1; day <= DateTime.DaysInMonth(year, month); ++day) {
            DateTime dt = new DateTime(year, month, day);
            if (dt.DayOfWeek == DayOfWeek.Monday) {
                return dt.AddDays(14);
            }
        }
        // this should never happen
        throw new Exception();
    }
}
Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193