Calculation of elapsed time in hours from date to current date, excluding weekends

I need to calculate in hours how much time has passed since the record was created to the current time. The hard part is that I have to exclude weekends from this.

I have been working on this for quite some time, and I'm just lost. Here is what I still have. Thank you in advance for your help.

   Dim MyStartTime As DateTime = "2010-08-09 07:00:00.000"
    Dim MyEndTime As DateTime = DateAdd("h", -1, Now())

    Dim MyHours As Integer = 0

    If Weekday(MyStartTime) > 1 And Weekday(MyStartTime) < 6 Then

        MyHours = DateDiff("h", MyStartTime, MyEndTime)

    ElseIf Weekday(MyStartTime) = 6 Then
        Dim EndTime
        date1.Date()
        MyHours = DateDiff("h", MyStartTime, MyEndTime)


    End If

    lblHours1.Text = MyHours

Which algorithm in VB.NET is best suited for this calculation?

+3
source share
3 answers

Here is one method:

Define the TimeSpan in hours for the entire range.

, . . , 00:00. , , 00:00. , .

3 , . , 0 :

NumberOfHoursBetweenDateAndNextMonday - . NumberOfHoursBetweenDateAndEarliestSaturday - . NumberOfFullWeekendHoursWithinRange - .

Dim MyHours As TimeSpan = MyEndTime - MyStartTime

'account for start being on a weekend
If (MyStartTime.DayOfWeek = vbSaturday Or vbSunday) Then
    'subtract number of hours until Monday at 00:00
    MyHours -= NumberOfHoursBetweenDateAndNextMonday(MyStartTime)

End If

If (MyEndTimeTime.DayOfWeek = vbSaturday Or vbSunday) Then
   'subtract number of hours elapsed after Saturday at 00:00
   MyHours -= NumberOfHoursBetweenDateAndEarliestSaturday(MyEndTime)
End If

MyHours -= NumberOfFullWeekendHoursWithinRange(MyStartTime, MyEndTime)
+2

TimeSpan .
 http://msdn.microsoft.com/en-us/library/269ew577.aspx

, , , , x 24

Dim MyHours As TimeSpan = MyEndTime-MyStartTime 
+2

, VB.net:

Public Function GetWorkdays(ByVal pstart As Date, ByVal pend As Date) As Integer

    If Weekday(pend) = 7 Then
        GetWorkdays = 7 - Weekday(pstart) + 5 * (DateDiff("ww", pstart, pend) - 1) + Weekday(pend) - 2
    Else
        GetWorkdays = 7 - Weekday(pstart) + 5 * (DateDiff("ww", pstart, pend) - 1) + Weekday(pend) - 1
    End If

End Function

:

setting two dates as GetWorkdays(pstart,pend), where as pstart is the start date and excerpt as the end date. It will calculate the number of days excluding weekends.

Give it a try. Mabuhay!

+1
source

Source: https://habr.com/ru/post/1758975/


All Articles