Results 1 to 3 of 3

Thread: Time Diff

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2003
    Posts
    419

    Time Diff

    Hello, I have two times that I would like to find the Hours, Minutes, Seconds between. I am using the following code:

    VB Code:
    1. Private Function TimeDiff(strTimeIn As String, strTimeOut As String)
    2. Dim hour As Long, min As Long, sec As Long
    3.  
    4.     sec = DateDiff("s", strTimeIn, strTimeOut)
    5.    
    6.     hour = Int(sec / 3600)
    7.     sec = sec - (hour * 3600)
    8.     min = Int(sec / 60)
    9.     sec = sec - (min * 60)
    10.     TimeDiff = Format(hour, "00") & ":" & Format(min, "00") & ":" & Format(sec, "00")
    11. End Function

    It works if say I have a TimeIn of 8:00:00AM and a TimeOut of 12:00:00 PM...but if I have a TimeIn of say 01:00:00 PM and a TimeOut of 08:00:00AM (Time diff should be 19 hours)...I get a timediff of -5:00:00. It is going 'back' in time instead of forward. How can I fix this?
    Code:
    If LostAngel.Tag = "Programming" then
       LostAngel.Caption = "Awake"
    Else
       LostAngel.Caption = "Dreaming of Code"
    End If

  2. #2
    Hyperactive Member
    Join Date
    Jun 2006
    Posts
    396

    Re: Time Diff

    Hi LostAngel;

    Are you using the full date or just the hh:mm:ss portion?

    Your second example won't work without complete dates and times.

    Hope this puts you on the right track.

  3. #3
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: Time Diff

    Try this:
    VB Code:
    1. Private Function TimeDiff(strTimeIn As String, strTimeOut As String)
    2.     Dim hour As Long, min As Long, sec As Long
    3.     Dim time1 As Date, time2 As Date
    4.    
    5.     time1 = CDate(strTimeIn)
    6.     time2 = CDate(strTimeOut)
    7.     sec = DateDiff("s", time1, time2)
    8.     Do While sec < 0 Then
    9.         time2 = time2 + 1 'add 1 day
    10.         sec = DateDiff("s", time1, time2)
    11.     Loop
    12.     hour = Int(sec / 3600)
    13.     sec = sec - (hour * 3600)
    14.     min = Int(sec / 60)
    15.     sec = sec - (min * 60)
    16.     TimeDiff = Format(hour, "00") & ":" & Format(min, "00") & ":" & Format(sec, "00")
    17. End Function

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width