get nth weekday of month in C#

Prasad picture Prasad · Jul 19, 2010 · Viewed 17.3k times · Source

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

How do i get the nth weekday of the month?

For ex.:

2nd Monday of "July 2010" = 07/12/2010.

Looking for a function like:

public DateTime GetNthWeekofMonth(DateTime date, int nthWeek, DayOfWeek dayofWeek)
{
//return the date of nth week of month
}

from the above, the parameters of the function will be ("Any Date in July 2010", 2, Monday).

Answer

SLaks picture SLaks · Jul 19, 2010

Use the following extension method:

public static class DateTimeExtensions
{
    ///<summary>Gets the first week day following a date.</summary>
    ///<param name="date">The date.</param>
    ///<param name="dayOfWeek">The day of week to return.</param>
    ///<returns>The first dayOfWeek day following date, or date if it is on dayOfWeek.</returns>
    public static DateTime Next(this DateTime date, DayOfWeek dayOfWeek) { 
        return date.AddDays((dayOfWeek < date.DayOfWeek ? 7 : 0) + dayOfWeek - date.DayOfWeek); 
    }
}

You can then write

new DateTime(2010, 07, 01).Next(DayOfWeek.Monday).AddDays((2 - 1) * 7);

Or, as a function:

public DateTime GetNthWeekofMonth(DateTime date, int nthWeek, DayOfWeek dayOfWeek) {
    return date.Next(dayOfWeek).AddDays((nthWeek - 1) * 7);
}

(I need to subtract one because date.Next(dayOfWeek) is already the first occurrence of that day)