26 | 02 | 2017

Calculate breaks (punch clock)

The code below is a sample on how to calculate timeperiods within a start and stop time. For instance when designing a punch clock it can be used to automaticly calculate breaks and to subtract this from it's working hours.

The code below is a part of a sample project that can be download from the bottom of this article. 


    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        '*** Code from VisibleVisual.com ********
        MsgBox(calculateBreakTime((Me.DateStart.Text), DateStop.Text))

    End Sub

    Private Function calculateBreakTime(ByVal startTime As String, ByVal stopTime As String)

        'Set the time to 0
        calculateBreakTime = 0

        'Convert string to timespan
        Dim start As TimeSpan = TimeSpan.Parse(startTime)
        Dim [stop] As TimeSpan = TimeSpan.Parse(stopTime)

        Dim breakStart As TimeSpan, breakStop As TimeSpan

        For i As Integer = 1 To 3 'this example shows 3 break moments. This can be extended. 
            If i = 1 Then
                'Break 1 between 10:00 and 10:15
                breakStart = TimeSpan.Parse("10:00")
                breakStop = TimeSpan.Parse("10:15")
            ElseIf i = 2 Then
                'Break 2 between 12:30 and 13:00
                breakStart = TimeSpan.Parse("12:30")
                breakStop = TimeSpan.Parse("13:00")
            ElseIf i = 3 Then
                'Break 3 between 15:00 and 15:15
                breakStart = TimeSpan.Parse("15:00")
                breakStop = TimeSpan.Parse("15:15")

                Throw New Exception("There are less breaks than counter 'i' holds")
            End If

            If start < breakStop AndAlso [stop] > breakStart Then
                'Calculate breakStart and stop when the break overlaps.
                If breakStart < start Then
                    breakStart = start
                End If
                If breakStop > [stop] Then
                    breakStop = [stop]
                End If

                'calculate the amount of break minutes
                Dim minuten As Integer
                minuten -= (breakStop - breakStart).Minutes

                calculateBreakTime = minuten 'return the value
            End If
    End Function

The sample source can be downloaded below. It holds a small form and some basic controls to show the functioning of the code.

 Calculate Breaks


Sign up now and upload your code to the website.

Help us to continue.....
Articles View Hits
Latest Articles