且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

取得周末之前的两个日期之间的天数

更新时间:2023-01-31 14:15:01

但可读的方法:

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 对象。由于周末 DayOfWeek 的数组,您可以使用 Enumerable.Contains 只采取不是周末日期的日期。最后一步是使用 Enumerable.Count 来执行查询,以获取工作天数。

The LINQ query first creates a range of integers from 0 to days (+1 because including last day). Then it creates Date objects via today.AddDays(days). Since weekend is an array of DayOfWeek you can use Enumerable.Contains to take only dates which are not weekend-dates. The last step is to execute the query by using Enumerable.Count to get the number of business days.

你可以通过提供 ParamArray 用于银行假期:

You could improve it by providing a ParamArray for the banking-holidays:

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

尽管如此,有银行假日。如果你有一个或多个,你可以传递一个真正的数组作为参数或单个对象像这样圣诞节:

That works as it is even if you don't have bank holiday days. If you have one or multiple you can either pass a real array as argument or single objects like here for christmas:

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)