如何让 String.Format 正确地用零和冒号填充它的时间

How to have String.Format properly pad it's time with zeroes and colons

我的 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 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