Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

How can I calculate the last business day of the month in .NET?

like image 806
joek1975 Avatar asked Nov 07 '08 18:11

joek1975


People also ask

How do I calculate last day in Excel?

Select the cell you will return the previous working day, enter formula =WORKDAY(TODAY(),-1,F2:F4) into the Formula Bar and press the Enter key. Finally format the cell as date format.

How do I calculate my workdays in a month?

The Excel NETWORKDAYS function calculates the number of working days between two dates. NETWORKDAYS automatically excludes weekends (Saturday and Sunday) and can optionally exclude a list of holidays supplied as dates.


2 Answers

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;
    }
}
like image 123
Thedric Walker Avatar answered Oct 08 '22 01:10

Thedric Walker


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
like image 44
Kibbee Avatar answered Oct 08 '22 01:10

Kibbee