Android Question Finding the number of seconds in a given time string

Dennis Glowack

Member
Licensed User
Given a Time String of "01:00:00", how would I calculate the number of seconds contained within the time presented? For example, the string shown represents an hour of time. I need to find out how to convert this time to 3600 seconds.

Thanks in advance
 
B4X: Copy
    Dim timestr As String = "01:00:00"
    DateTime.TimeFormat = "HH:mm:ss"
    Dim time As Long = DateTime.TimeParse(timestr)
    Dim seconds As Int = ((DateTime.GetHour(time)*3600) + (DateTime.GetMinute(time)*60) + DateTime.GetSecond(time))
    Log(seconds)
 
Upvote 0
B4X: Copy
    Dim timestr As String = "01:00:00"
    DateTime.TimeFormat = "HH:mm:ss"
    Dim time As Long = DateTime.TimeParse(timestr)
    Dim seconds As Int = ((DateTime.GetHour(time)*3600) + (DateTime.GetMinute(time)*60) + DateTime.GetSecond(time))
    Log(seconds)
Thank you very much. I understand your code. This should help me a lot going forward with other time calculations.
 
Upvote 0
I don't recommend using DateTime features for values that do not represent specific time instances (time instance example: February 8, 1999 12:34:56).
You will encounter all kinds of unexpected issues.

You can use this method to parse the time period:
Code: Copy
Sub HHMMSSToPeriod (time As String) As Period
    Dim p As Period
    Dim m As Matcher = Regex.Matcher("(\d\d?):(\d\d):(\d\d)", time)
    If m.Find Then
        p.Initialize
        p.Hours = m.Group(1)
        p.Minutes = m.Group(2)
        p.Seconds = m.Group(3)
    End If
    Return p
End Sub

Dim p As Period = HHMMSSToPeriod("01:23:45")
Log(p)
Period comes from DateUtils library.
 
Upvote 0
how would I calculate the number of seconds contained within the time presented?
Why could it not be something as trivial as this since all he is looking for is the total seconds:
Code: Copy
Dim str As String = "01:23:45"
    Dim strArray() As String = Regex.Split(":",str)
    Log(strArray(0)*3600 + strArray(1)*60+ strArray(2))  'displays: 5025
 
Upvote 0
Why could it not be something as trivial as this since all he is looking for is the total seconds
Missed the fact that the OP is only interested in the total seconds.

I like the usage of Period here as this is exactly the purpose of Period, to represent a period of time and not a specific time instance.
 
Upvote 0
Back
Top