Reputation: 1598
I have the following piece of code in my VB program. What I noticed is that the timer label will show the time 59:59 then 0:00.
What I would like to have happen is the timer to display 1:00:00 but can't seem to get this correct.
Private Sub tmrShowTimer_Tick(sender As Object, e As EventArgs) Handles tmrShowTimer.Tick
' Timer Event to handle the StopWatch counting the "Show Timer" hopefully this doesn't get too full.
Dim tsShowElapsed As TimeSpan = Me.stwShowTimer.Elapsed
If tsShowElapsed.Hours >= 1 Then
lblShowTimer.Font = New Font(lblShowTimer.Font.Name, 18)
End If
lblShowTimer.Text = String.Format("{1:#0}:{2:00}",
Math.Floor(tsShowElapsed.TotalHours),
tsShowElapsed.Minutes,
tsShowElapsed.Seconds)
End Sub
What am I missing to get this to correctly format?
Upvotes: 1
Views: 85
Reputation: 1792
It can be a little more compact, like so:
lblShowTimer.Text = tsShowElapsed.ToString(If(tsShowElapsed.Hours > 0, "h\:mm\:ss", "m\:ss").ToString)
But yeah, I think you'll always have to use a conditional to handle this.
Upvotes: 1
Reputation: 11773
Since you have a check for hours you could do this
Private Sub tmrShowTimer_Tick(sender As Object, e As EventArgs) Handles tmrShowTimer.Tick
' Timer Event to handle the StopWatch counting the "Show Timer" hopefully this doesn't get too full.
'Me.stwShowTimer.Elapsed is a timespan
If Me.stwShowTimer.Elapsed.Hours >= 1 Then
lblShowTimer.Font = New Font(lblShowTimer.Font.Name, 18)
lblShowTimer.Text = Me.stwShowTimer.Elapsed.ToString("h\:mm\:ss")
Else
lblShowTimer.Text = Me.stwShowTimer.Elapsed.ToString("m\:ss")
End If
End Sub
Upvotes: 1
Reputation: 1598
So I managed to edit the program to involve a conditional, there might be abetter way to do this but here is what I have:
If tsShowElapsed.Hours > 0 Then
strFormat = "{0:#0}:{1:#0}:{2:00}"
Else
strFormat = "{1:#0}:{2:00}"
End If
lblShowTimer.Text = String.Format(strFormat,
Math.Floor(tsShowElapsed.TotalHours),
tsShowElapsed.Minutes,
tsShowElapsed.Seconds)
Upvotes: 0