How do I determine if a given date is the Nth weekday of the month?

前端 未结 8 1784
无人及你
无人及你 2020-12-03 11:14

Here is what I am trying to do: Given a date, a day of the week, and an integer n, determine whether the date is the nth day of the month.

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 11:25

    In case you want a list of dates for a span of time (not just one) for the Nth DayOfWeek of a Month, you can use this:

    internal static List GetDatesForNthDOWOfMonth(int weekNum, DayOfWeek DOW, DateTime beginDate, DateTime endDate)
    {
        List datesForNthDOWOfMonth = new List();
        int earliestDayOfMonth = 1;
        int latestDayOfMonth = 7;
        DateTime currentDate = beginDate;
    
        switch (weekNum)
        {
            case 1:
                earliestDayOfMonth = 1;
                latestDayOfMonth = 7;
                break;
            case 2:
                earliestDayOfMonth = 8;
                latestDayOfMonth = 14;
                break;
            case 3:
                earliestDayOfMonth = 15;
                latestDayOfMonth = 21;
                break;
            case 4:
                earliestDayOfMonth = 22;
                latestDayOfMonth = 28;
                break;
        }
    
        while (currentDate < endDate)
        {
            DateTime dateToInc = currentDate;
            DateTime endOfMonth = new DateTime(dateToInc.Year, dateToInc.Month, DateTime.DaysInMonth(dateToInc.Year, dateToInc.Month));
            bool dateFound = false;
            while (!dateFound)
            {
                dateFound = dateToInc.DayOfWeek.Equals(DOW);
                if (dateFound)
                {
                    if ((dateToInc.Day >= earliestDayOfMonth) && 
                        (dateToInc.Day <= latestDayOfMonth))
                    {
                        datesForNthDOWOfMonth.Add(dateToInc);
                    }
                }
                if (dateToInc.Date.Equals(endOfMonth.Date)) continue;
                dateToInc = dateToInc.AddDays(1);
            }
            currentDate = new DateTime(currentDate.Year, currentDate.Month, 1);
            currentDate = currentDate.AddMonths(1);
        }
        return datesForNthDOWOfMonth;
    }
    

    ...and call it this way:

    // This is to get the 1st Monday in each month from today through one year from today
    DateTime beg = DateTime.Now;
    DateTime end = DateTime.Now.AddYears(1);
    List dates = GetDatesForNthDOWOfMonth(1, DayOfWeek.Monday, beg, end);
    // To see the list of dateTimes, for verification
    foreach (DateTime d in dates)
    {
        MessageBox.Show(string.Format("Found {0}", d.ToString()));
    }
    

    You could get the 2nd Friday of each month like so:

    List dates = GetDatesForNthDOWOfMonth(2, DayOfWeek.Friday, beg, end);
    

    ...etc.

提交回复
热议问题