当前位置:  开发笔记 > 编程语言 > 正文

如何确定给定月份的最后一个工作日?

如何解决《如何确定给定月份的最后一个工作日?》经验,为你挑选了5个好方法。

如何计算.NET中该月的最后一个工作日?



1> Kibbee..:

假设工作日是星期一到星期五(这不考虑假期),这个函数应该返回正确的答案:

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



2> Thedric Walk..:

我会在周一到周五的工作周这样做:

var holidays = new List{/* 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;
    }
}



3> 小智..:

我能想到这个简单的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;
}



4> Brian Knobla..:

首先,获取本月的最后一天.然后继续递减,直到你要么超过月初,要么达到验证为"营业日"的日期.



5> shsteimer..:

通用,伪代码:

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


如果只有一个月没有任何工作日这样的事情.
推荐阅读
喜生-Da
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有