Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the last DayOfWeek of a month

Tags:

c#

datetime

Given a DateTime and a DayOfWeek should return the date of the last DayOfWeek of that month.

E.g. 1st-March-2009 and Sunday would return 29th-March-2009

like image 668
Ryan Avatar asked Mar 08 '09 11:03

Ryan


1 Answers

Can't find a handy one-liner but this one works:

static DateTime LastDayOfWeekInMonth(DateTime day, DayOfWeek dow)
{
    DateTime lastDay = new DateTime(day.Year, day.Month, 1).AddMonths(1).AddDays(-1);
    DayOfWeek lastDow = lastDay.DayOfWeek;

    int diff = dow - lastDow;

    if (diff > 0) diff -= 7;

    System.Diagnostics.Debug.Assert(diff <= 0);

    return lastDay.AddDays(diff);
}
like image 182
Henk Holterman Avatar answered Oct 13 '22 01:10

Henk Holterman