Big Smile
Big Smile

Reputation: 1124

C# - Check if a given date is the Fifth week day of a month?

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:

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

Answers (1)

NetMage
NetMage

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

Related Questions