C# - What is the best way to get a list of the weeks in a month, given a starting weekday?

 // Get the weeks in a month

 DateTime date = DateTime.Today;
 // first generate all dates in the month of 'date'
 var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n));
 // then filter the only the start of weeks
 var weekends = from d in dates
                where d.DayOfWeek == DayOfWeek.Monday
                select d;

public static List<DateTime> GetWeeks(
    this DateTime month, DayOfWeek startOfWeek)
{
    var firstOfMonth = new DateTime(month.Year, month.Month, 1);
    var daysToAdd = ((Int32)startOfWeek - (Int32)month.DayOfWeek) % 7;
    var firstStartOfWeek = firstOfMonth.AddDays(daysToAdd);

    var current = firstStartOfWeek;
    var weeks = new List<DateTime>();
    while (current.Month == month.Month)
    {
        weeks.Add(current);
        current = current.AddDays(7);
    }

    return weeks;
}

Here's a solution (effectively one line) using C# 3.0/LINQ, in case you're interested:

var month = new DateTime(2009, 2, 1);
var weeks = Enumerable.Range(0, 4).Select(n => month.AddDays(n * 7 - (int)month.DayOfWeek + 1)).TakeWhile(monday => monday.Month == month.Month);

Tags:

C#

Datetime