December 28th 2004
Converting Time String to Seconds
I just had to implement something for the first time that I knew is easy, but I just didn’t like all the approaches. I thought to myself, “This should be doable in just a few lines.” I had even written code like this before, but since I am not using the unreleased version currently, I didn’t have the ability for block level dims, and I just couldn’t bring myself to dimming off a few more variables.
Finally, I had a revelation. I wrote it in only 7 lines of code.
Problem: You are given a string, such as “1:23″ or “20:47:16″. Convert this to an absolute time in seconds. For example, “23″ should yield 23 seconds, “1:23″ should yield 83 seconds, and “1:00:00″ should yield 3600 seconds.
Solution:
Protected Function TimeToSeconds(inputString As String) As Integer
Dim multiplier,time As Integer
Dim parts() As String = Split( theInputString, ":" )
multiplier = 1
While UBound( parts ) >= 0
time = time + val( trim( parts.pop ) ) * multiplier
multiplier = multiplier * 60
Wend
This is the most elegant solution I can think of to this problem. The idea is to split the string into an array, and then treat it as a stack. Pop each item off, and for each item you pop off, you increase the multiplier by 60. I also inserted a trim because I am accepting this as user input, and if they type in “1: 23″ I want it to still work :). This code will fail if you try to give it time that has a day value (for example, “1:23:45:56″). So, we can make the code less elegant, but still get it done:
Protected Function TimeToSeconds(inputString As String) As Integer
Dim multiplier,time As Integer
Dim multipliers() As Integer = Array( 365, 24, 60, 60 )
Dim parts() As String = Split( inputString, ":" )
multiplier = 1
While UBound( parts ) >= 0
time = time + val( trim( parts.pop ) ) * multiplier
If ubound( multipliers ) < 0 Then Return time
multiplier = multiplier * multipliers.pop
Wend
Return time
End Function
And, walah! You now have a nice, compact solution to a pretty common problem.