Reputation: 1124
I am a little confused about how to check if a given date day is the day that appears the fifth time in a month. For example, the below are some days of week that appears 5 times in a month:
Thursday 29th March 2018
Friday 30th March 2018
Saturday 31st March 2018
Saturday 29th April 2018
I want a method that will return true
or false
if a given date day is the fifth week day of a month.
I have tried the below code from this question but this method only returns the first date that starts the fifth week cycle.
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;
}
Thank you
Upvotes: 1
Views: 860
Reputation: 26907
Isn't any date over 28 going to be the fifth occurrence of that week day?
public static bool IsFifthWeek(DateTime d) => d.Day > 28;
Upvotes: 5