Question about String.Format to display time

时间:2019-01-09 21:52:29

标签: .net vb.net

I am trying to display time (from a stopwatch and timer) like so:

btnButton1.Text = String.Format("{0}{1}:{2:00}", timespan1.Hours, timespan1.Minutes, timespan1.Seconds)
btnButton2.Text = String.Format("{0}{1}:{2:00}", timespan2.Hours, timespan2.Minutes, timespan2.Seconds)

Could anyone please tell me how I can change the formatting of the time like so:
Button1: 0:00 where the first 0 is minute and the second 00 are seconds.
Button2: 000:00 where the first 000 are minutes and the second 00 are seconds.

Any help would be greatly appreciated!

1 个答案:

答案 0 :(得分:0)

由于TimeSpan.TotalMinutes返回一种Double类型,因此您需要将其作为Integer呈现。
有个陷阱,Integer转换会舍入中间点(90.590分钟和30秒将转换为91,所以您'ld以91:30结尾)。
改用Math.Truncate保留值的整数部分(Math.Round也将取整)。

Dim timespan1 As TimeSpan = New TimeSpan(1, 9, 1)
Dim timespan2 As TimeSpan = New TimeSpan(3, 3, 30)

btnButton1.Text = String.Format("{0:#0}:{1:00}", Math.Truncate(timespan1.TotalMinutes), timespan1.Seconds)
btnButton2.Text = String.Format("{0:#0}:{1:00}", Math.Truncate(timespan2.TotalMinutes), timespan2.Seconds)  

btnButton1.Text = "69:01"
btnButton2.Text = "183:30"

格式也可以是{0:N0}:{1:00}

或者,如果您不想在0部分中看到前导seconds,请使用{0:N0}:{1:N0},它将给出:

69:1
183:30