get nth weekday of month in C# [duplicate]
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).
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)
One possible algorithm:
- Start from the 1st of the month.
- Move forward one day at a time until you get the Day of Week you're looking for.
- Add (7 * N) to the date you're on to get the date you want.
Duplicate can be found here: How do I determine if a given date is the Nth weekday of the month?
int d = date.Day;
return date.DayOfWeek == dow && (d-1)/7 == (n-1);
IEnumerable<DateTime> WeekdaysFrom( DateTime start )
{
DateTime weekday = start.Add( TimeSpan.FromDays(1) );
while( weekday < DateTime.MaxValue.Subtract( TimeSpan.FromDays(1) ) )
{
while( weekday.DayOfWeek == DayOfWeek.Saturday || weekday.DayOfWeek == DayOfWeek.Sunday )
{
weekday.Add( TimeSpan.FromDays(1) );
}
yield return weekday;
}
}
DateTime NthWeekday( DateTime month, int n )
{
return WeekdaysFrom( new DateTime( month.year, month.month, 1 ) ).Skip(n-1).First();
}
精彩评论