Converting HH:MM:SS Into Seconds (And Reversed!)
Hello!
I wrote a little program to convert HH:MM:SS into Seconds. Here is the code:
vb Code:
Private Function HMSToSeconds(ByRef HMS As String) As Int32
Try
Dim Str As String = HMS
Dim ColonCount As Int32 = 0
For i As Int32 = 0 To Str.Count - 1 Step 1
If Str(i) = ":"c Then
ColonCount += 1
End If
Next
If ColonCount <= 2 Then
Dim StrArray() As String = Str.Split(":"c)
Dim Sec As Int32 = 0
Dim Factor As Int32 = 1
For i As Int32 = StrArray.Count - 1 To 0 Step -1
Sec += StrArray(i) * Factor
Factor *= 60
Next
Return Sec
Else
MsgBox("Incorrect format. Use HH:MM:SS")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
I also did the reverse: (Seconds into HH:MM:SS)
vb Code:
Private Function SecondsToHMS(ByRef Seconds As Int32) As String
Try
Dim Sec As Int32 = Seconds
Dim Factor As Int32 = 60 ^ 2
Dim HMS As String = Nothing
Dim Counter As Int32 = 0
For i As Int32 = 2 To 0 Step -1
Counter = 0
Factor = 60 ^ i
Do Until Sec < Factor
Sec -= Factor
Counter += 1
Loop
If Counter < 10 Then
HMS += "0"
End If
HMS += Counter.ToString
If i > 0 Then
HMS += ":"
End If
Next
Return HMS
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
I hope you can find a use for this.
~NinjaNic
Re: Converting HH:MM:SS Into Seconds (And Reversed!)
Or:
vb.net Code:
Private Function HMSToSeconds(hms As String) As Int32
Dim seconds As TimeSpan
If TimeSpan.TryParseExact(hms, "hh\:mm\:ss", Nothing, seconds) Then
Return Convert.ToInt32(seconds.TotalSeconds)
Else
'Invalid format.
End If
End Function
Private Function SecondsToHMS(seconds As Int32) As String
Return TimeSpan.FromSeconds(seconds).ToString("hh\:mm\:ss")
End Function
Note that the method parameters are not declared ByRef, as there's no good reason to do so.
Re: Converting HH:MM:SS Into Seconds (And Reversed!)
Wow, I didn't know about this TimeSpan class. Guess I should do my studying.
Re: Converting HH:MM:SS Into Seconds (And Reversed!)
Quote:
Originally Posted by
NinjaNic
I didn't know about this TimeSpan class.
It's actually a structure.
Re: Converting HH:MM:SS Into Seconds (And Reversed!)
Thats a very useful sample. Thanks!
Re: Converting HH:MM:SS Into Seconds (And Reversed!)
I prefer my code because HMSToSeconds can work in either format HH:MM:SS / MM:SS and the Hour part can have as many digits as needed.
Re: Converting HH:MM:SS Into Seconds (And Reversed!)
I guess you could always put your code in the "Else" case, if the TimeSpan.TryParse can't handle the format.:rolleyes: