How to convert this timespan

Y

YXQ

Hello,
I want to convert the timespan (1.12:25:23) to 1day 12hour 25min 23sec, how
to do it? thank you.
 
M

Martin H.

Hello YXQ,

That format you provided is not a timespan, but seems to be a custom
string format. Therefore, the information has to be "cut" out of the
string. If it was just a TimeSpan value (in a timespan variable), then
you could just use the "Days", "Hours", "Minutes" and "Seconds"
properties of the timespan variable to get your result.

To deal with a string in the specified format, you could use this method:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
MsgBox(Convert("1.12:25:23"))
End Sub

Private Function Convert(ByVal TimeSpanString As String) As String
Dim retVal As String
Dim posi As Integer, t As Integer
Dim iTSS As String, iDays As String, iSplit() As String

iTSS = Trim(TimeSpanString)
posi = InStr(TimeSpanString, ".")

If posi > 0 Then
iDays = Strings.Left(iTSS, posi - 1)
iTSS = Strings.Right(iTSS, iTSS.Length - posi)
Else
iDays = 0
End If

iSplit = Split(iTSS, ":")

retVal = iDays & "day "

For t = 0 To UBound(iSplit)

If t > 2 Then
Exit For 'Just in case the string is longer
End If

retVal &= iSplit(t)
Select Case t
Case 0
retVal &= "hour "

Case 1
retVal &= "min "

Case 2
retVal &= "sec"
End Select
Next

Return retVal
End Function

Best regards,

Martin
 
J

Jay B. Harlow [MVP - Outlook]

Have you tried TimeSpan.Parse?

Dim s As String = "1.12:25:23"
Dim time As TimeSpan = TimeSpan.Parse(s)

Alternatively you can use TimeSpan.TryParse.

Dim s As String = "1.12:25:23"
Dim time As TimeSpan
If TimeSpan.TryParse(s, time) Then
' Its a valid time span
End If
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top