Android Question Hours and minutes between two times [Solved]

Colin Evans

Active Member
Licensed User
Longtime User
Hi, is there a simple way to get the number of hours and minutes between to times,

i.e a = 08:45 and b = 12:15

so c = b - a should be 3hrs 30mins

I've looked at DateUtils but couldn't seem to figure a simple way of achieving it, any help greatly appreciated
 

Mahares

Expert
Licensed User
Longtime User
I've looked at DateUtils but couldn't seem to figure a simple way of achieving it, any help greatly appreciated
DateUtils works if you have an instance of time, like date and time. But here you only have time, so one way is to parse the 2 times:
B4X:
Dim a As String = "12:15"
    Dim b As String= "08:45"
    Dim h , m As Int
    Dim t1() As String =Regex.Split(":",a)
    Dim t2() As String =Regex.Split(":",b)
    Dim t As Int = t1(0) *60 +t1(1) -t2(0) * 60 - t2(1)    
    h=Floor(t/60)
    m= t Mod 60
    Log($"${h}:${m}"$)  'will display 3:30
It would be easier if it had the date component.
 
Upvote 0

PoppaBart

Member
Try this. I used edittext fields for the times.

B4X:
Sub Button1_Click
    Dim PerDiff As Period
    Dim StartHrs, StartMin, EndHrs, EndMin As Int
    
    StartHrs = edtStartHrs.Text
    StartMin = edtStartMin.Text
    EndHrs = edtEndHrs.Text
    EndMin = edtEndMin.Text
    
    Dim TimeA As Long = DateUtils.SetDateAndTime(2020, 10, 10, StartHrs, StartMin, 0)
    Dim TimeB As Long = DateUtils.SetDateAndTime(2020, 10, 10, EndHrs, EndMin, 0)
    
    PerDiff = DateUtils.PeriodBetween(TimeA, TimeB)
    
    lblAnswer.Text = PerDiff.Hours & ":" & PerDiff.Minutes

End Sub
 
Upvote 0

Colin Evans

Active Member
Licensed User
Longtime User
Hi Thanks for the input, I did figure it out along the lines you gave

B4X:
Sub CalcHrsMins(shrs As Int, smins As Int, ehrs As Int, emins As Int)
    Dim stotalMins As Int = ((shrs * 60) + smins)
    Dim etotalmins As Int = ((ehrs * 60) + emins)
    Dim ResultMins As Int = etotalmins - stotalMins
    Log("result " & ResultMins)
    HoursDiff = ResultMins / 60
    MinsDiff = ResultMins Mod 60
End Sub

Many thanks
 
Upvote 0
Top