可能重复:
How do I determine if a given date is Nth weekday of the month?
我如何获得当月的第n个工作日?
例如:
2010年7月的第二个星期一= 2010年12月7日。
寻找类似的功能:
public DateTime GetNthWeekofMonth(DateTime date, int nthWeek, DayOfWeek dayofWeek)
{
//return the date of nth week of month
}
从上面可以看出,函数的参数是(“2010年7月的任何日期”,2,星期一)。
答案 0 :(得分:22)
使用以下扩展方法:
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);
}
}
然后你可以写
new DateTime(2010, 07, 01).Next(DayOfWeek.Monday).AddDays((2 - 1) * 7);
或者,作为一个功能:
public DateTime GetNthWeekofMonth(DateTime date, int nthWeek, DayOfWeek dayOfWeek) {
return date.Next(dayOfWeek).AddDays((nthWeek - 1) * 7);
}
(我需要减去一个,因为date.Next(dayOfWeek)
已经是那天的第一次出现了)
答案 1 :(得分:2)
一种可能的算法:
答案 2 :(得分:0)
可在此处找到重复项: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);
答案 3 :(得分:0)
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();
}