这是我想要做的:给定日期,星期几和整数n
,确定日期是否是n
该月的第几天.
例如:
输入1/1/2009,Monday,2
将是假的,因为1/1/2009
不是第二个星期一
输入
11/13/2008,Thursday,2
将返回true,因为它是第二个星期四
如何改进此实施?
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n) { int d = date.Day; return date.DayOfWeek == dow && (d/ 7 == n || (d/ 7 == (n - 1) && d % 7 > 0)); }
Robert Wagne.. 12
您可以更改一周的检查,以便函数读取:
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){ int d = date.Day; return date.DayOfWeek == dow && (d-1)/7 == (n-1); }
除此之外,它看起来非常好,效率很高.
您可以更改一周的检查,以便函数读取:
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){ int d = date.Day; return date.DayOfWeek == dow && (d-1)/7 == (n-1); }
除此之外,它看起来非常好,效率很高.
答案来自这个网站.复制/粘贴此处以防网站丢失.
public static DateTime FindTheNthSpecificWeekday(int year, int month,int nth, System.DayOfWeek day_of_the_week) { // validate month value if(month < 1 || month > 12) { throw new ArgumentOutOfRangeException("Invalid month value."); } // validate the nth value if(nth < 0 || nth > 5) { throw new ArgumentOutOfRangeException("Invalid nth value."); } // start from the first day of the month DateTime dt = new DateTime(year, month, 1); // loop until we find our first match day of the week while(dt.DayOfWeek != day_of_the_week) { dt = dt.AddDays(1); } if(dt.Month != month) { // we skip to the next month, we throw an exception throw new ArgumentOutOfRangeException(string.Format("The given month has less than {0} {1}s", nth, day_of_the_week)); } // Complete the gap to the nth week dt = dt.AddDays((nth - 1) * 7); return dt; }