一個天真,但可讀的做法:
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,因爲包括最後一天)。然後它通過today.AddDays(days)
創建Date
對象。由於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)
什麼是正常工作時間? – Crono