vb.net – 将时间转换为hh:mm:ss格式的程序

前端之家收集整理的这篇文章主要介绍了vb.net – 将时间转换为hh:mm:ss格式的程序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使一个简单的程序将时间转换为hh:mm:ss格式.但是对于某些特定的输入值,它会产生不正确的时间格式.这是我试过的:
Public Class Form1
    Dim Hours,Minutes,Seconds As Integer

    Private Sub btnReset_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnReset.Click
        lblHours.Text = "00"
        lblMinutes.Text = "00"
        lblSeconds.Text = "00"
        txtTimeSeconds.Text = ""
        txtFormattedTime.Text = ""
    End Sub

    Private Sub btnCalculate_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnCalculate1.Click
        Seconds = Integer.Parse(txtTimeSeconds.Text)
        Hours = Seconds / 3600
        Seconds = Seconds Mod 3600
        Minutes = Seconds / 60
        Seconds = Seconds Mod 60

        lblHours.Text = Hours.ToString.PadLeft(2,"0"c)
        lblMinutes.Text = Minutes.ToString.PadLeft(2,"0"c)
        lblSeconds.Text = Seconds.ToString.PadLeft(2,"0"c)

        txtFormattedTime.Text = Hours.ToString.PadLeft(2,"0"c) & ":" & Minutes.ToString.PadLeft(2,"0"c) & ":" & Seconds.ToString.PadLeft(2,"0"c)
    End Sub
End Class

当输入值为30时,它工作:

当输入值为31时,它不起作用:

我做错了什么?如何解决这个问题?

.NET中有一个叫做 TimeSpan的类,它使你的代码变得简单而优雅.

例:

dim iSecond as double = 0 'Total number of seconds
Dim iSpan As TimeSpan = TimeSpan.FromSeconds(iSecond)

lblHours.Text = iSpan.Hours.ToString.PadLeft(2,"0"c)
lblMinutes.Text = iSpan.Minutes.ToString.PadLeft(2,"0"c)
lblSeconds.Text = iSpan.Seconds.ToString.PadLeft(2,"0"c)

txtFormattedTime.Text = iSpan.Hours.ToString.PadLeft(2,"0"c) & ":" & _
                        iSpan.Minutes.ToString.PadLeft(2,"0"c) & ":" & _
                        iSpan.Seconds.ToString.PadLeft(2,"0"c)

猜你在找的VB相关文章