Kib*_*bee 14
假设工作日是星期一到星期五(这不考虑假期),这个函数应该返回正确的答案:
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
Run Code Online (Sandbox Code Playgroud)
The*_*ker 12
我会在周一到周五的工作周这样做:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我能想到这个简单的C#代码,它为您提供当月的最后一个工作日.这只需要周六或周日作为假期.应手动处理国家特定的当地假日.
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;
}
Run Code Online (Sandbox Code Playgroud)
通用,伪代码:
Day day = getLastDayOfMonth
int days = getDaysInMonth
for i = days to 0
if day is weekday
if day is not holiday
return day
end if
end if
day = prevDay
days--
end for
throw exception because no business day was found in the month
Run Code Online (Sandbox Code Playgroud)