Reputation: 27
I have 1 question regarding the time span/duration management.
Currently, I have a record in the database representing a time in mmss
format. Example: 5030 that suppose to mean 50 minutes and 30 seconds.
And I wanted to display this at my web page in this format:
Is there any way that I could achieve this? The data stored inside the DB is in string format. I am currently using VB.NET language in an ASP.NET application.
I searched all over the internet but I keep on getting results for representing time, rather than a duration.
Currently, I am doing it in this way, but I am still unable to get the hour to be displayed:
If arrayValueInside.Length > 0 Then
If arrayValueInside(0) = "STOPPING TIME" Then
Dim strTime As String = arrayValueInside(1).Trim()
Select Case strTime.Length
Case 1
strTime = strTime & "s"
Case 2
strTime = strTime & "s"
Case 3
strTime = strTime.Substring(0, 1) & "m " & strTime.Substring(1, 2) & "s"
Case 4
strTime = strTime.Substring(0, 2) & "m " & strTime.Substring(2, 2) & "s"
' If Integer.Parse(strTime) >= 6000 Then
' Return strTime.Substring(0, 2) + "m" + strTime.Substring(1, 2) + "s"
' Else
' End If
Case 5
strTime = strTime.Substring(0, 3) & "m " & strTime.Substring(3, 2) & "s"
End Select
Please let me know if there is anything not clear in the information I provided.
Upvotes: 0
Views: 164
Reputation: 32248
Since the time format is presented in the form mmss
, I think it should also be considered that the minutes value, in some cases, might exceed "99"
and could be expressed by 3 (or maybe more) numbers.
The TimeSpan structure has an internal mechanism to calculate the units of time which can be useful here. All the units are transposed and measured in Days. If one unit has a value that exceeds it's maximum, it will be recalculated in the next unit.
So, 70 minutes will become 1 hour and 10 minutes.
Here, the 2 rightmost characters are considered to represents the seconds value; all the other (2 or more) represent minutes.
Dim input As String = "12845"
Dim seconds As Integer = Integer.Parse(input.Substring(input.Length - 2, 2))
Dim minutes As Integer = Integer.Parse(input.Substring(0, input.Length - 2))
Dim ts As New TimeSpan(0, 0, minutes, seconds)
Dim TimeFormat = $"{ts.Hours}h {ts.Minutes}m {ts.Seconds}s"
The TimeFormat string will be 2h 8m 45s
.
If string interpolation is not available, use the String.Format() method:
Dim TimeFormat = String.Format("{0}h {1}m {2}s", ts.Hours, ts.Minutes, ts.Seconds)
A slightly modified method, which doesn't return a unit measure if that unit value is 0.
If the input string is "12045"
, the previous method would return 2h 0m 45s
. This one will return 2h 45s
.
Dim TimeFormat As String() = New String() {
(If(ts.Hours > 0, ts.Hours & "h", "")),
(If(ts.Minutes > 0, " " & ts.Minutes & "m", "")),
(If(ts.Seconds > 0, " " & ts.Seconds & "s", ""))
}
Dim output As String = $"{TimeFormat(0)}{TimeFormat(1)}{TimeFormat(2)}"
Upvotes: 1