How to find the 3rd Friday in a month with C#?

后端 未结 19 973
野的像风
野的像风 2020-11-27 06:07

Given a date (of type DateTime), how do I find the 3rd Friday in the month of that date?

19条回答
  •  一整个雨季
    2020-11-27 06:45

    My reasoning goes like this

    • the 15th is the first possible "third Friday" (1,8,15)
    • therefore we're looking for the first Friday on or after the 15th
    • DayOfWeek is an enumeration starting with 0 for Sunday
    • Therefore you have to add an offet of 5-(int)baseDay.DayOfWeek to the 15th
    • Except that the above offset can be negative, which we fix by adding 7, then doing modulo 7.

    In code:

    public static DateTime GetThirdFriday(int year, int month)
    {
       DateTime baseDay = new DateTime(year, month, 15);
       int thirdfriday = 15 + ((12 - (int)baseDay.DayOfWeek) % 7);
       return new DateTime(year, month, thirdfriday);
    }
    

    Since there are only 7 possible results, you could also do this:

      private readonly static int[] thirdfridays =
          new int[] { 20, 19, 18, 17, 16, 15, 21 };
    
      public static int GetThirdFriday(int year, int month)
      {
         DateTime baseDay = new DateTime(year, month, 15);
         return thirdfridays[(int)baseDay.DayOfWeek];
      }
    

提交回复
热议问题