How to get the date of a day in a month in certain year? [closed]

First I’d create a DateTime using the first day of that month.

From there, I’d pick the DayOfWeek property, do some math (subtract/add) to find the right date that week that matched the date you want.

From there, I’d keep calling DateTime.AddDays(7), and return those values until the month property rolled over.

I’d write a function that did this, that takes a year, a month, and a DayOfWeek. It would return an IEnumerable<DateTime>, and yield return each value.

Something like this:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        foreach (var date in DayOfWeek.Monday.OccurrencesInMonth(year: 2011, month: 8))
        {
            Console.WriteLine(date);
        }
    }
}

public static class DayOfWeekExtensions
{
    public static IEnumerable<DateTime> OccurrencesInMonth(this DayOfWeek targetDayOfWeek, int year, int month)
    {
        var firstDayInYear = new DateTime(year, month, 1);
        var currentDay = firstDayInYear.Next(targetDayOfWeek);

        while (currentDay.Month == month)
        {
            yield return currentDay;
            currentDay = currentDay.AddDays(7);
        }
    }
}

public static class DateTimeExtensions
{
    public static DateTime Next(this DateTime current, DayOfWeek dayOfWeek)
    {
        int offsetToNextOccurrence = dayOfWeek - current.DayOfWeek;
        if (offsetToNextOccurrence < 0)
            offsetToNextOccurrence += 7;
        return current.AddDays(offsetToNextOccurrence);
    }
}

8/1/2011 12:00:00 AM
8/8/2011 12:00:00 AM
8/15/2011 12:00:00 AM
8/22/2011 12:00:00 AM
8/29/2011 12:00:00 AM

Leave a Comment