How can I calculate the last business day of the month in .NET?
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.
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.
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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With