我从另一个问题中使用此代码:
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){
int d = date.Day;
return date.DayOfWeek == dow && (d-1)/7 == (n-1);
}
工作正常。但它不会检查最后一天(对我而言,当n = 5时)。如何修改?
感谢。
答案 0 :(得分:9)
以下方法检查给定日期是一周中某一周的最后日期。
private bool IsLastOfMonth(DateTime date)
{
var oneWeekAfter = date.AddDays(7);
return oneWeekAfter.Month != date.Month;
}
所以有新的方法,它只是检查星期一
private bool IsLastMonday(DateTime date)
{
if (date.DayOfWeek != DayOfWeek.Monday)
return false; // it is not monday
// the next monday is...
var oneWeekAfter = date.AddDays(7);
// and is it in same month?, if it is, that means its not last monday
return oneWeekAfter.Month != date.Month;
}
答案 1 :(得分:2)
让我们看看3月30日,
d = 30,
(date.DayOfWeek == DayOfWeek.Friday) == true,
(30-1)=29, 29/7 = 4
4 == (5-1)
所以它有效
要仅检查DayOfWeek是否为最后一个,您可以使用
return date.AddDays(7).Month != date.Month;