string 格式化时间 (HH:MM:SS)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7089974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting Time (HH:MM:SS)
提问by Brian
I'm taking values from Numeric Ups and Downs for Hours, Minutes and Seconds.
我正在从数字上升和下降中获取小时、分钟和秒的值。
The problem is that, for example, if the time for example is 9.15 am it will show as 9:15:0
问题是,例如,如果时间是 9.15 am,它将显示为 9:15:0
What I want to do is format them so if any of the values(Hours, Minutes or seconds) is less than 10, it will add a 0 before the number so as the number shows as 09:15:00.
我想要做的是格式化它们,因此如果任何值(小时、分钟或秒)小于 10,它将在数字前添加一个 0,以便数字显示为 09:15:00。
What I tried is this but it does not work:
我试过的是这个,但它不起作用:
Sub BtnSetClick(sender As Object, e As EventArgs)
lbl8.Visible = True
Dim nmTime As String = nmHour.Value.ToString + nmMin.Value.ToString + nmSec.Value.ToString
lblST.Text.Format(nmTime.ToString, "HH:MM:SS")
lblST.Text = (nmTime)
lblST.Visible = True
End Sub
回答by Hans Olsson
You seem to be doing it a bit backward by converting everything to string multiple times, try something like this:
通过多次将所有内容转换为字符串,您似乎有点落后,请尝试以下操作:
Dim ts As new TimeSpan(CInt(nmHour.Value), CInt(nmMin.Value), CInt(nmSec.Value))
lblST.Text = ts.ToString("HH:MM:SS")
The documentation for TimeSpan.ToStringis useful.
TimeSpan.ToString的文档很有用。
Edit: Updated the code to reflect Tim's comment about datatype.
编辑:更新了代码以反映 Tim 关于数据类型的评论。
回答by Tim
Try this:
尝试这个:
Sub BtnSetClick(ByVal sender As Object, ByVal e As EventArgs)
lbl8.Visible = True
Dim nmTime As String = nmHour.Value.ToString().PadLeft(2, '0') + nmMin.Value.ToString().PadLeft(2, '0') + nmSec.Value.ToString().PadLeft(2, '0')
lblST.Text = nmTime
lblST.Visible = True
End Sub
回答by pingoo
try using the TimeSpan object, it should do all the hard work for you!
尝试使用 TimeSpan 对象,它应该为您完成所有艰苦的工作!
Dim nmTime As New TimeSpan(nmHour.Value, nmMin.Value, nmSec.Value)
lblST.Text = nmTime.ToString
lblST.Visible = True