获取两个日期之间的天数,不包括周末
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取两个日期之间的天数,不包括周末相关的知识,希望对你有一定的参考价值。
我使用下面的代码减去两个日期
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,依此类推
答案
一种天真但可读的方法:
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)
另一答案
它应该是:
Select day = startDay.AddDays(d)
由于指定范围的开始日期可能并不总是如此。
以上是关于获取两个日期之间的天数,不包括周末的主要内容,如果未能解决你的问题,请参考以下文章