2

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

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),它会给出不正确的结果。

我知道这是因为循环而发生的,但我想不出办法来克服这个问题。谁能给我一个建议,解决方案?

谢谢

4

2 回答 2

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
于 2012-01-29T17:50:53.307 回答
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
于 2017-03-29T16:31:41.553 回答