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

后端 未结 19 966
野的像风
野的像风 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:51

    Here is my two cents... An optimized solution without unnecessary loops or tests :

    public static DateTime ThirdFridayOfMonth(DateTime dateTime)
    {
        int day = dateTime.Day;
        return dateTime.AddDays(21 - day - ((int)dateTime.DayOfWeek + 37 - day) % 7);
    }
    

提交回复
热议问题