Calculate Hours Worked (Military Time Used)
So i was given the task of writing a new employee payroll proggy custom to my employers work. One issue was calculating, on the fly, the hours worked.
For example, one employee clocks in then later logs time out, immidiatly on clicking hours box, they should see a sub total of those current hours worked for that shift. I had alot of trouble gathering information for this and finally just wrote my own code. Do to lack of knowledge this may not be the best sub function in the world, but it does EXACTLY what i needed it to do, and since there is so little out there for help, i figured i would provide it here for others.
to use the sub is easy
select a textbox or richtext to have focus then fill in the blanks. i'll put axample at end
the Sub Code:
Public Sub countHours(ByVal timeIn As String, ByVal timeOut As String, ByVal hours As TextBox, ByVal ooPs As Object)
Try
Dim firstTime As Integer = Convert.ToInt16(timeIn)
Dim secondTime As Integer = Convert.ToInt16(timeOut)
If secondTime > firstTime Then
Dim hrsTimeIn As DateTime = DateTime.ParseExact(timeIn, "HHmm", CultureInfo.InvariantCulture)
Dim hrsTimeOut As DateTime = DateTime.ParseExact(timeOut, "HHmm", CultureInfo.InvariantCulture)
Dim totalTime As TimeSpan = hrsTimeOut.Subtract(hrsTimeIn)
hours.Text = totalTime.ToString
ElseIf firstTime > secondTime Then
Dim zeroHour As String = "0000"
Dim tfourHour As String = "2359"
Dim oneMin As TimeSpan
oneMin = New TimeSpan(0, 1, 0)
Dim midnight As DateTime = DateTime.ParseExact(zeroHour, "HHmm", CultureInfo.InvariantCulture)
Dim twentyFour As DateTime = DateTime.ParseExact(tfourHour, "HHmm", CultureInfo.InvariantCulture)
Dim hrsTimeIn As DateTime = DateTime.ParseExact(timeIn, "HHmm", CultureInfo.InvariantCulture)
Dim hrsTimeOut As DateTime = DateTime.ParseExact(timeOut, "HHmm", CultureInfo.InvariantCulture)
Dim firstDay As TimeSpan = twentyFour.Subtract(hrsTimeIn).Add(oneMin)
Dim secondDay As TimeSpan = hrsTimeOut.Subtract(midnight)
Dim totalTime As TimeSpan = firstDay.Add(secondDay)
hours.Text = totalTime.ToString
End If
Catch ex As Exception
ooPs.focus()
MsgBox("Incorrect Time Value Entered, " & vbCrLf & "Please Use Military Time. " & vbCrLf & "exp. 1:35PM = 1335")
End Try
End Sub
use like this
the Use Code:
Private Sub txtTransHours_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtTransHours.GotFocus
countHours(txtTransTimeIn.Text, txtTransTimeOut.Text, txtTransHours, txtTransTimeIn)
End Sub
it works! and it's simple! if anyone has better way, please post it!
PS. this code also works for night shifts! like 11:00P to 7:00A and stuff!
Night shift example
http://i669.photobucket.com/albums/v...tempTime01.png
Night shift example 2
http://i669.photobucket.com/albums/v...tempTime02.png
Re: Calculate Hours Worked (Military Time Used)
Is it possible to format the output in decimal format or any other format?