Android Code Snippet [B4X] Convert milliseconds to string

This code converts milliseconds to hours, minutes and seconds:

B4X:
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 $"$1.0{hours}:$2.0{minutes}:$2.0{seconds}"$
End Sub

It is somewhat similar to DateTime.Time however DateTime.Time works with ticks that represent a specific time instance and is therefore affected by the time zone.
 

LucaMs

Expert
Licensed User
Longtime User
With milliseconds:
B4X:
Private Sub ConvertTicksToTimeString(t As Long) As String
    Dim Hours, Minutes, Seconds, Milliseconds As Int

    Hours = t / DateTime.TicksPerHour
    Minutes = (t Mod DateTime.TicksPerHour) / DateTime.TicksPerMinute
    Seconds = (t Mod DateTime.TicksPerMinute) / DateTime.TicksPerSecond
    Milliseconds = t Mod 1000
    
    Return $"$2.0{Hours}:$2.0{Minutes}:$2.0{Seconds}:$2.0{Milliseconds}"$
End Sub



Return $"$1.0{hours}:$2.0{minutes}:$2.0{seconds}"$
Why 1.0 for hours?!
 

aeric

Expert
Licensed User
Longtime User
Why 1.0 for hours?!
Hours can be at least 1 integer and I think milliseconds should show in 3 digit, e.g 1:02:59:003

1677238473727.png


B4X:
Return $"$2.0{Hours}:$2.0{Minutes}:$2.0{Seconds}:$3.0{Milliseconds}"$
 
Top