Borami O Borami O - 10 months ago 56 Question

VB.Net Cast string larger than 6 characters to timespan. For example hhhhh:mm:ss

I am getting an integer string. It could be 512 or it could be 15215534. The first one would be 5 min. 12 seconds. The 2nd number would be 1521 hours, 55 minutes, and 34 seconds. This is what I am using now:

Dim input As String
Dim time As TimeSpan
Dim length As Integer
length = input.Length

'Return 0 if null
If length = 0 Then
result = 0
Return result
End If

time = New TimeSpan(0, input.Substring(0, length - 4), input.Substring(length - 4, 2), input.Substring(length - 2, 2), 0)

The code now errors for inputs with 4 character lengths or smaller. Is my best solution to use if statements for the different lengths or is there a better, built in way to do this?


I would do it as follows:

Dim input as String = "2133"
input = input.PadLeft(5, '0')

Dim seconds = Convert.ToInt32(input.Substring(input.Length - 2, 2))
Dim minutes = Convert.ToInt32(input.Substring(input.Length - 4, 2))
Dim hours = Convert.ToInt32(input.Substring(0, input.Length - 4))

Dim time = new TimeSpan(hours, minutes, seconds)

Basically, you know you'll have at most 2 digits for seconds at the end, the next 2 would be minutes and anything preceding that would be hours.

The challenge would be if you don't have minutes or hours in your string (or even just single seconds) - So, you pad your string with enough 0s at the start to ensure you won't get any issues and then parse out the numbers you need.

I wrote it in C# and converted it, but I hope it still works.