我试图使一个简单的程序将时间转换为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的类,它使你的代码变得简单而优雅.
原文链接:/vb/255666.html例:
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)