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

2020-01-25 01:15发布

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

标签: c# .net datetime
17条回答
看我几分像从前
2楼-- · 2020-01-25 01:57

I pass this the DateTime for the start of the month I am looking at.

    private DateTime thirdSunday(DateTime timeFrom)
    {
        List<DateTime> days = new List<DateTime>();
        DateTime testDate = timeFrom;

        while (testDate < timeFrom.AddMonths(1))
        {
            if (testDate.DayOfWeek == DayOfWeek.Friday)
            {
                days.Add(testDate);
            }
            testDate = testDate.AddDays(1);
        }

        return days[2];
    }
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-01-25 01:58

Slightly more optimized version:

    DateTime Now = DateTime.Now;

    DateTime TempDate = new DateTime(Now.Year, Now.Month, 1);

    // find first friday
    while (TempDate.DayOfWeek != DayOfWeek.Friday)
        TempDate = TempDate.AddDays(1);

    // add two weeks
    TempDate = TempDate.AddDays(14);
查看更多
SAY GOODBYE
4楼-- · 2020-01-25 02:00

I haven't tested this, but since the third Friday can't possibly occur before the 15th of the month, create a new DateTime, then just increment until you get to a Friday.

DateTime thirdFriday= new DateTime(yourDate.Year, yourDate.Month, 15);

while (thirdFriday.DayOfWeek != DayOfWeek.Friday)
{
   thirdFriday = thirdFriday.AddDays(1);
}
查看更多
贪生不怕死
5楼-- · 2020-01-25 02:02

Here's my algorithm:

  1. Find the number of days until the upcoming Friday.
  2. Initialize a counter and set it to 1. Subtract seven days from the date returned from [1], then compare the month from the date returned against the date returned from (1).
    1. If the months are not equal, return the counter from [2].
    2. If the months are equal, recurse into [2] and add 1 to the counter created in [2].

The counter will give you the nth Friday of the month for that date (or its upcoming Friday).

查看更多
爷、活的狠高调
6楼-- · 2020-01-25 02:02

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);
}
查看更多
登录 后发表回答