C. Clements
C. Clements

Reputation: 23

How do I calculate Hours between dates with a 8-hour work day and accounting for weekends? (VB.net)

I need some help calculating hours worked between two dates, but with an 8-hour work day. I also need to adjust for weekends so I don't say someone took longer then they actually did. I am using VB.net

For example, date1 is 1/23/2020 9:00:00 AM, the start date, and date2 is 1/27/2020 1:30:00 PM, the finish time.

If I run this code:

Dim hours As double = DateDiff(DateInterval.hour, date1, date2)

it would give me the total hours, but would include weekends and not filter it for an 8 hour day.

How can I filter out workday times and weekends? Any help in refining this would be appreciated

Upvotes: 0

Views: 398

Answers (2)

dbasnett
dbasnett

Reputation: 11773

Simple loop

    Dim td As DateTime
    If endDate < startDate Then
        'switch
        td = endDate
        endDate = startDate
        startDate = td
    End If
    Dim hours As Integer = 0
    td = startDate
    While td < endDate
        If td.DayOfWeek <> DayOfWeek.Saturday AndAlso td.DayOfWeek <> DayOfWeek.Sunday Then
            hours += 8
        End If
        td = td.AddDays(1)
    End While

Upvotes: 0

Anu6is
Anu6is

Reputation: 2658

One possible option

'Get all days between the start date and the end date
Dim midDays As Date() = Enumerable.Range(0, endDate.Subtract(startDate.AddDays(1)).Days).Select(Function(offset) startDate.AddDays(offset)).ToArray
'Filter out any weekend days
Dim weekdays As Date() = midDays.Where(Function(day) day.DayOfWeek <> DayOfWeek.Saturday AndAlso day.DayOfWeek <> DayOfWeek.Sunday).ToArray
'Assume all days are a full 8 hours
Dim hoursWorked As Decimal = weekdays.Count * 8

This essentially creates a list of all days between the start and end date. Remove weekends from the list and calculates 8 hours for each remaining day.

Of course you would then add the hours from the first and last day to the total.

Upvotes: 2

Related Questions