VB.NET - 计算两个日期之间的日期与排除

时间:2012-01-29 17:19:25

标签: vb.net days

我正在计算两个日期之间的天数,不包括星期六星期日。到目前为止我已经编写了这段代码

Dim startDay As Integer
Dim endDay As Integer
Dim days As Integer
Dim count As Integer

startDay = dtpStartDate.Value.DayOfWeek
endDay = dtpEndDate.Value.DayOfWeek

For days = startDay To endDay
    If days = 0 Or days = 6 Then           'Sunday = 0, Saturday = 6
        count += 1
    End If
Next

    lblNoOfDays.Text = count

如果您在同一周内选择两个日期,它可以正常工作。 (例如:1月23日至1月27日,给出结果5) 但是,如果我将它们设置为不同周的日期,(例如:1月23日至1月30日,结果为1),则结果不正确。

我知道这是因为循环,但我想不出办法克服这个问题。任何人都可以给我一个建议,解决方案??

谢谢

2 个答案:

答案 0 :(得分:7)

Dim count = 0
Dim totalDays = (dtpEndDate - dtpStartDate).Days

For i = 0 To totalDays
    Dim weekday As DayOfWeek = startDate.AddDays(i).DayOfWeek
    If weekday <> DayOfWeek.Saturday AndAlso weekday <> DayOfWeek.Sunday Then
        count += 1
    End If
Next

lblNoOfDays.Text = count

答案 1 :(得分:1)

此函数计算两个日期之间的非周末天数:

    Public Shared Function WorkingDaysElapsed(ByVal pFromDate As Date, ByVal pToDate As Date) As Integer

        Dim _elapsedDays As Integer = 0
        Dim _weekendDays As DayOfWeek() = {DayOfWeek.Saturday, DayOfWeek.Sunday}

        For i = 0 To (pToDate - pFromDate).Days
            If Not _weekendDays.Contains(pFromDate.AddDays(i).DayOfWeek) Then _elapsedDays += 1
        Next

        Return _elapsedDays

    End Function