B4J Question Time in seconds between two times formatted 'HHmmss' as strings

ElliotHC

Active Member
Licensed User
I need to get the integer difference in seconds between two time strings.

They are formatted like this.

HHmmss (e.g. 081256)

I have two times and I need the difference in seconds between the two string times.
 

emexes

Expert
Licensed User
If you need to account for summer time / daylight saving then consider DateUtils library PeriodBetween, but otherwise consider this:
B4X:
Sub SecondsBetween(T1 As String, T2 As String) As Int
   
    If T1.Length <> 6 Or T2.Length <> 6 Then
        Return 0    'dude, what are you doing?!?!
    End If

    Dim H1 As Int = T1.SubString2(0, 2)
    Dim M1 As Int = T1.SubString2(2, 4)
    Dim S1 As Int = T1.SubString2(4, 6)

    Dim H2 As Int = T2.SubString2(0, 2)
    Dim M2 As Int = T2.SubString2(2, 4)
    Dim S2 As Int = T2.SubString2(4, 6)

    Dim T1Seconds As Int = H1 * 3600 + M1 * 60 + S1
    Dim T2Seconds As Int = H2 * 3600 + M2 * 60 + S2

    Return (T2Seconds - T1Seconds + 86400) Mod 86400    'works across midnight, eg 233000 to 003000 should be 1 hour = 3600 seconds

End Sub
 
Last edited:
Upvote 0
Top