[英]string.Format of a timer?
I've a time ticker event, I want to write it to a label in format ( hours:minutes:seconds 00:00:00 ) it does not print the 0 values! 我有一个时间自动收报机事件,我想以格式(小时:分钟:秒00:00:00)将其写入标签,它不会打印0值! it shows like ::1 when starts to count... what to do?
当开始计算时,它显示为:: 1 ...怎么办? Solved, thanks for all replies
解决了,谢谢你的回复
private void timer_Tick(object sender, EventArgs e)
{
seconds++;
if(seconds == 59)
{
minutes++;
seconds = 0;
}
if(minutes == 59)
{
hours++;
minutes = 0;
}
this.label1.Text = string.Format("{0:##}:{1:##}:{2:##}", hours, minutes, seconds);
}
A better method is using DateTime and TimeSpan objects. 更好的方法是使用DateTime和TimeSpan对象。 For example:
例如:
DataTime start = <set this somehow>
void timer_Tick(...)
{
var elapsed = DateTime.Now - start;
label1.Text = string.Format("{0:HH:mm:ss}", elapsed);
}
Best would be to use TimeSpan and DateTime as others have said. 最好的是使用TimeSpan和DateTime,正如其他人所说的那样。 If you want to continue using your current method, though, change the format string to:
但是,如果要继续使用当前方法,请将格式字符串更改为:
string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds)
The 00
format will cause two digits to always be printed, even zeroes. 00
格式将导致始终打印两位数,甚至为零。
尝试一下思考实验 - 将秒和分钟设置为58,然后浏览代码,看看会发生什么......
使用TimeSpan
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.