[Solved] Get Last Date of Given Month and Year in c#


So you want a method which takes a year and a month as parameter and returns dates. Those dates should be the last dates of all weeks in that month, optionally also of following months.

This should work then:

public static IEnumerable<DateTime> GetLastWeekDatesOfMonth(int year, int month, DayOfWeek firstDayOfWeek = DayOfWeek.Monday, bool includeLaterMonths = false)
{ 
    DateTime first = new DateTime(year, month, 1);
    int daysOffset = (int)firstDayOfWeek - (int)first.DayOfWeek;
    if (daysOffset < 0)
        daysOffset = 7 - Math.Abs(daysOffset);
    DateTime firstWeekDay = first.AddDays(daysOffset);
    DateTime current = firstWeekDay.AddDays(-1); // last before week start
    if (current.Month != month)
        current = current.AddDays(7);
    yield return current;
    if (includeLaterMonths)
    {
        while (true)
        {
            current = current.AddDays(7);
            yield return current;
        }
    }
    else
    { 
        while((current = current.AddDays(7)).Month == month)
            yield return current;
    }
}

Your sample:

var lastDates = GetLastWeekDatesOfMonth(2016, 1, DayOfWeek.Sunday, true);
foreach (DateTime dt in lastDates.Take(6))
    Console.WriteLine(dt.ToShortDateString());

solved Get Last Date of Given Month and Year in c#