获取两个日期之间的天数,不包括周末

时间:2014-04-03 12:34:10

标签: .net vb.net winforms date

我使用以下代码

减去两个日期
Dim OpenDate, ClosedDate As DateTime
dim Result as String
OpenDate = Convert.ToDateTime(some string contain date and time)
ClosedDate = Convert.ToDateTime(some string contain date and time)
Result = ClosedDate.Subtract(OpenDate).ToString

它的格式正确(day.hour:minute:second)

,效果正常

我需要的是

如果关闭和开放日期之间的期间包含星期五或星期六从结果中减去

实施例。如果结果9.03:02:10包含2周六和周五,则必须是6.03:02:10,依此类推

2 个答案:

答案 0 :(得分:6)

一种天真但可读的方法:

Public Shared Function GetBusinessDays(startDay As DateTime, endDay As DateTime) As Integer
    Dim today = Date.Today
    Dim weekend = {DayOfWeek.Saturday, DayOfWeek.Sunday}
    Dim businessDays = 
        From d In Enumerable.Range(0, (endDay.Date - startDay.Date).Days + 1)
        Select day = today.AddDays(d)
        Where Not weekend.Contains(day.DayOfWeek)
    Return businessDays.Count()
End Function

测试:

Dim days As Int32 = GetBusinessDays(Date.Now, Date.Now.AddDays(9))
Console.Write(days) ' 7

LINQ查询首先创建一个从0到天的整数范围(+1因为包括最后一天)。然后,它通过Date创建today.AddDays(days)个对象。由于weekend是一个DayOfWeek数组,因此您可以使用Enumerable.Contains仅使用非周末日期的日期。最后一步是使用Enumerable.Count执行查询以获取工作日数。

您可以通过为银行假日提供ParamArray来改进它:

Public Shared Function GetBusinessDays(startDay As DateTime, endDay As DateTime, ParamArray bankHoliday As Date()) As Integer
    Dim today = Date.Today
    Dim nonWorkingDays = New HashSet(Of Date)(bankHoliday)
    Dim weekend = {DayOfWeek.Saturday, DayOfWeek.Sunday}
    Dim businessDays =
        From d In Enumerable.Range(0, (endDay - startDay).Days + 1)
        Select day = today.AddDays(d)
        Where Not weekend.Contains(day.DayOfWeek) AndAlso Not nonWorkingDays.Contains(day)
    Return businessDays.Count()
End Function

即使你没有银行假日,这也是有效的。如果你有一个或多个,你可以传递一个真实的数组作为参数,或者像这里的单个对象传递圣诞节:

Dim christmas = New Date(2014, 12, 25)
Dim days As Int32 = GetBusinessDays(Date.Now, Date.Now.AddDays(9), christmas)

或少数单个对象:

Dim christmasEve = New Date(2014, 12, 24)
Dim days As Int32 = GetBusinessDays(Date.Now, Date.Now.AddDays(9), christmasEve, christmas)

答案 1 :(得分:1)

它应该是:

Select day = startDay.AddDays(d)

由于指定范围的开始日期可能并不总是今天。