【问题标题】:How to have String.Format properly pad it's time with zeroes and colons如何让 String.Format 正确地用零和冒号填充它的时间
【发布时间】:2015-10-24 14:56:39
【问题描述】:

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

为了正确格式化我缺少什么?

【问题讨论】:

    标签: vb.net string timespan stopwatch


    【解决方案1】:

    所以我设法编辑程序以包含条件,可能有更好的方法来做到这一点,但这是我所拥有的:

        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)
    

    【讨论】:

      【解决方案2】:

      它可以更紧凑一点,像这样:

      lblShowTimer.Text = tsShowElapsed.ToString(If(tsShowElapsed.Hours > 0, "h\:mm\:ss", "m\:ss").ToString)
      

      但是,是的,我认为你总是必须使用条件来处理这个问题。

      【讨论】:

        【解决方案3】:

        既然你有几个小时的检查,你可以这样做

        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
        

        【讨论】:

        • 哦,对了,我可以把这些组合成一个条件
        猜你喜欢
        • 2013-02-25
        • 2015-04-29
        • 2013-07-06
        • 2020-06-06
        • 2021-12-05
        • 2016-09-07
        • 1970-01-01
        • 2021-11-27
        • 1970-01-01
        相关资源
        最近更新 更多