我对如何检查某个特定日期是否是一个月内第五次出现的日子感到有些困惑。例如,以下是一周中的某些天,每月出现5次:
Thursday 29th March 2018
Friday 30th March 2018
Saturday 31st March 2018
Saturday 29th April 2018
如果给定日期日是一个月的第五周,我想要一个返回true
或false
的方法。
我已经尝试了this question中的以下代码,但此方法仅返回开始第五周周期的第一个日期。
public DateTime? FifthDay(DayOfWeek dayOfWeek, byte monthNum, int year)
{
var searchDate = new DateTime(year, monthNum, 1);
var weekDay = searchDate.DayOfWeek;
if (weekDay == dayOfWeek)
{
searchDate = searchDate.AddDays(28);
}
for (DateTime d = searchDate; d < d.AddDays(7); d = d.AddDays(1))
{
if (d.DayOfWeek == dayOfWeek)
{
searchDate = searchDate.AddDays(28);
break;
}
}
if (searchDate.Month == monthNum)
return searchDate;
return null;
}
谢谢
答案 0 :(得分:5)
不是28岁以上的任何日期是该周工作日的第五次出现吗?
public static bool IsFifthWeek(DateTime d) => d.Day > 28;