2014-04-03 183 views
0

我用下面的代碼獲取天數兩個日期之間不包括週末

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:分:秒)

我需要什麼是

如果關閉和打開日期之間的時間段包含從結果

防爆週五或週六減法。如果造成9.03:02:10包含2個週六和週五它必須是6.03:02:10等

+0

什麼是正常工作時間? – Crono

回答

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,因爲包括最後一天)。然後它通過today.AddDays(days)創建Date對象。由於weekendDayOfWeek的數組,因此您可以使用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) 
相關問題