Vb.net 如何让String.Format正确填充它';用零和冒号表示时间
我的VB程序中有以下代码。我注意到,计时器标签将显示时间59:59,然后是0:00 我想让计时器显示1:00:00,但似乎无法正确显示Vb.net 如何让String.Format正确填充它';用零和冒号表示时间,vb.net,string,timespan,stopwatch,Vb.net,String,Timespan,Stopwatch,我的VB程序中有以下代码。我注意到,计时器标签将显示时间59:59,然后是0:00 我想让计时器显示1:00:00,但似乎无法正确显示 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 g
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
要使其正确格式化,我缺少了什么?因此我设法编辑程序,使其包含一个条件,可能有更好的方法来实现这一点,但我有以下几点:
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)
它可以更紧凑一些,如下所示:
lblShowTimer.Text = tsShowElapsed.ToString(If(tsShowElapsed.Hours > 0, "h\:mm\:ss", "m\:ss").ToString)
但是,是的,我认为你必须始终使用条件来处理这个问题。因为你有一个小时支票,所以你可以这样做
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
哦,对了,我可以把这些组合成一个条件