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

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

    Sorry to jump in late on this... Might help someone else tho.

    Begin rant: Loops, yuck. Too much code, yuck. Not Generic Enough, yuck.

    Here's a simple function with a free overload.

    public DateTime DateOfWeekOfMonth(int year, int month, DayOfWeek dayOfWeek, byte weekNumber)
    {
        DateTime tempDate = new DateTime(year, month, 1);
        tempDate = tempDate.AddDays(-(tempDate.DayOfWeek - dayOfWeek));
    
        return
            tempDate.Day > (byte)DayOfWeek.Saturday
                ? tempDate.AddDays(7 * weekNumber)
                : tempDate.AddDays(7 * (weekNumber - 1));
    }
    
    public DateTime DateOfWeekOfMonth(DateTime sender, DayOfWeek dayOfWeek, byte weekNumber)
    {
        return DateOfWeekOfMonth(sender.Year, sender.Month, dayOfWeek, weekNumber);
    }
    

    Your usage:

    DateTime thirdFridayOfMonth = DateOfWeekOfMonth(DateTime.Now, DayOfWeek.Friday, 3);
    

提交回复
热议问题