Android Question Dividing Time by 3

Sagenut

Expert
Licensed User
Longtime User
I think he want to obtain something like
3:10
3:10
3:10 (about)
Intended as 3 minutes and 10 seconds, or hours and minutes.
 
Upvote 0

emexes

Expert
Licensed User
convert to seconds (or minutes?):

9 * 60 + 29 = 569 seconds

divide by 3

569 / 3 = 189.667 seconds

convert back to mm:ss

round to nearest: Floor(189.667 + 0.5) = 190 seconds
or round down: Floor(189.667) = 189 seconds

Floor(189 / 60) = 3 minutes
189 - 3 * 60 = 9 seconds

03:09

same math works for hh:mm as well as for mm:ss
since there are both 60 minutes in hour and 60 seconds in minute
 
Last edited:
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
The important point here is not to use DateTime.Time or TimeParse. These methods are relevant when working with time instances, not durations.

B4X:
    Dim t As Long = ParseTimeDuration("09:29")
    t = t / 3
    Log(ConvertMillisecondsToString(t))

Private Sub ParseTimeDuration(HHMM As String) As Long
    Dim s() As String = Regex.Split(":", HHMM)
    Dim t As Long = s(0) * DateTime.TicksPerHour + s(1) * DateTime.TicksPerMinute
    If s.Length = 3 Then
        t = t + s(2) * DateTime.TicksPerSecond
    End If
    Return t
End Sub

Private Sub ConvertMillisecondsToString(t As Long) As String
    Dim hours, minutes, seconds As Int
    hours = t / DateTime.TicksPerHour
    minutes = (t Mod DateTime.TicksPerHour) / DateTime.TicksPerMinute
    seconds = (t Mod DateTime.TicksPerMinute) / DateTime.TicksPerSecond
    Return $"$2.0{hours}:$2.0{minutes}:$2.0{seconds}"$
End Sub
 
Upvote 0

Alhootti

Active Member
The important point here is not to use DateTime.Time or TimeParse. These methods are relevant when working with time instances, not durations.

B4X:
    Dim t As Long = ParseTimeDuration("09:29")
    t = t / 3
    Log(ConvertMillisecondsToString(t))

Private Sub ParseTimeDuration(HHMM As String) As Long
    Dim s() As String = Regex.Split(":", HHMM)
    Dim t As Long = s(0) * DateTime.TicksPerHour + s(1) * DateTime.TicksPerMinute
    If s.Length = 3 Then
        t = t + s(2) * DateTime.TicksPerSecond
    End If
    Return t
End Sub

Private Sub ConvertMillisecondsToString(t As Long) As String
    Dim hours, minutes, seconds As Int
    hours = t / DateTime.TicksPerHour
    minutes = (t Mod DateTime.TicksPerHour) / DateTime.TicksPerMinute
    seconds = (t Mod DateTime.TicksPerMinute) / DateTime.TicksPerSecond
    Return $"$2.0{hours}:$2.0{minutes}:$2.0{seconds}"$
End Sub
yes i mean this
Thanks
 
Upvote 0
Top