Return Nth Weekday of Month My goal is to obtain the nth weekday of a given month. Parameters are a date from a given month and the nth weekday I'm trying to obtain. It returns the Nth Weekday of the month if it exist and returns DateTime.MinValue othewise. For my purposes weekdays are M-F.

Is there a more elegant or efficient way to implement this logic? My implementation feels crude, basically a while loop that counts weekdays until it finds the desired date or the end of the month.

    public static DateTime getNthWeekdayOfMonth(DateTime date, int nthWeekday)
    {
        //Valid inputs are greater than 0 but less than 24 
        if (nthWeekday &gt; 23 || nthWeekday &lt; 1)
            return DateTime.MinValue;

        //start with 1st day of month from date param
        DateTime currentDay = new DateTime(date.Year, date.Month, 1);

        int i = 0;
        while(i &lt; nthWeekday &amp;&amp; currentDay.Month == date.Month)
        {
            if (currentDay.DayOfWeek != DayOfWeek.Saturday &amp;&amp; currentDay.DayOfWeek != DayOfWeek.Sunday)
            {
                i++;
                if(i == nthWeekday)
                    return currentDay;
            }
            currentDay = currentDay.AddDays(1);
        }
        return DateTime.MinValue;
    }


Usage

var date1 = getNthWeekdayOfMonth(new DateTime(2015, 8, 11), 22);
//returns DateTime.MinValue
var date2 = getNthWeekdayOfMonth(new DateTime(2015, 8, 11), 21);
//returns 8/31/2015
var date3 = getNthWeekdayOfMonth(new DateTime(2015, 8, 11), 1);
//returns 8/3/2015
int i = 0;
    while(i &lt; nthWeekday &amp;&amp; currentDay.Month == date.Month)
    {
        if (currentDay.DayOfWeek != DayOfWeek.Saturday &amp;&amp; currentDay.DayOfWeek != DayOfWeek.Sunday)
        {
            i++;
            if(i == nthWeekday)
                return currentDay;
        }
        currentDay = currentDay.AddDays(1);
    }



Your while loop is a little messy let's clean that up first, and you should also have an early continue statement in there.

Let me show you what I mean:

int i = 1;
while(i &lt;= nthWeekday &amp;&amp; currentDay.Month == date.Month)
{
    bool isWeekendDay = currentDay.DayOfWeek == DayOfWeek.Saturday || currentDay.DayOfWeek == DayOfWeek.Sunday;

    if (isWeekendDay)
    {
        currentDay = currentDay.AddDays(1);
        continue;
    }
    if (i == nthWeekday) 
    {
        return currentDay;
    }
    currentDay = currentDay.AddDays(1);
    i++;
}


This is a lot cleaner, and shows exactly what our intent is.  It is much easier to read.

You shouldn't nest if statements inside of other if statements if you don't have to, it can get very confusing.