How to determine the last business day in a given month?

Assuming business days are monday to friday (this doesn't account for holidays), this function should return the proper answer:

Function GetLastBusinessDay(ByVal Year As Integer, ByVal Month As Integer) As DateTime
    Dim LastOfMonth As DateTime
    Dim LastBusinessDay As DateTime

    LastOfMonth = New DateTime(Year, Month, DateTime.DaysInMonth(Year, Month))

    If LastOfMonth.DayOfWeek = DayOfWeek.Sunday Then 
        LastBusinessDay = LastOfMonth.AddDays(-2)
    ElseIf LastOfMonth.DayOfWeek = DayOfWeek.Saturday Then
        LastBusinessDay = LastOfMonth.AddDays(-1)
    Else
        LastBusinessDay = LastOfMonth
    End If

    Return LastBusinessDay

End Function

I could think of this simple C# code which gives you the last business day of current month. This only takes Saturday or Sunday as holidays. Country specific local holidays should be handled manually.

private DateTime GetLastBusinessDayOfCurrentMonth()
{
    var lastDayOfCurrentMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month,  DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));

    if(lastDayOfCurrentMonth.DayOfWeek == DayOfWeek.Sunday)
        lastDayOfCurrentMonth = lastDayOfCurrentMonth.AddDays(-2);
    else if(lastDayOfCurrentMonth.DayOfWeek == DayOfWeek.Saturday)
        lastDayOfCurrentMonth = lastDayOfCurrentMonth.AddDays(-1);

    return lastDayOfCurrentMonth;
}

I would do it like this for a Monday through Friday business week:

var holidays = new List<DateTime>{/* list of observed holidays */};
DateTime lastBusinessDay = new DateTime();
var i = DateTime.DaysInMonth(year, month);
while (i > 0)
{
  var dtCurrent = new DateTime(year, month, i);
  if(dtCurrent.DayOfWeek < DayOfWeek.Saturday && dtCurrent.DayOfWeek > DayOfWeek.Sunday && 
   !holidays.Contains(dtCurrent))
    {
      lastBusinessDay = dtCurrent;
      i = 0;
    }
    else
    {
      i = i - 1;
    }
}

Tags:

.Net