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}"$
 

LucaMs

Expert
Licensed User
Longtime User
The purpose of this code is to convert a duration value to string. Time instance is not a duration value. The result is more or less meaningless.
I don't understand what you mean by "duration" and "Time instance" (as if Time were a class).
I thought DateTime.TimeParse (my second test) returned the ticks of the time (time or duration can be the same thing).
 

LucaMs

Expert
Licensed User
Longtime User
It depends on the timezone and DST.
This is the problem, in fact you wrote:
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.
Despite the help of ChatGPT, I still haven't managed to get two functions to handle a duration in the format: "HH:mm:ss:SSS" both ways, from string to ticks and vice versa.

However, this is most likely not the right place for this question.
 
Top