VB.NET - counting days between two dates with exclusions

限于喜欢 提交于 2019-12-24 02:28:25

问题


I'm trying to count the days between two dates, excluding Saturdays and Sundays. I've written this code so far

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

It works fine if you choose the two dates within the same week. (ex: 23rd Jan to 27th Jan, gives the result 5) But if I set them to dates in different weeks, (ex : 23rd Jan to 30th Jan, gives the result 1), it gives incorrect results.

I know it happens because of the loop but I can't think of a way to overcome this. Can anyone give me a suggestion, solution??

Thank you


回答1:


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



回答2:


This function calculates the non-weekend days between two dates:

    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


来源:https://stackoverflow.com/questions/9055073/vb-net-counting-days-between-two-dates-with-exclusions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!