string.Format of a timer?

ana*_*kos 2 c#

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! it shows like ::1 when starts to count... what to do? 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);
        }
Run Code Online (Sandbox Code Playgroud)

suk*_*kru 5

A better method is using DateTime and TimeSpan objects. For example:

DataTime start = <set this somehow>

void timer_Tick(...)
{
   var elapsed = DateTime.Now - start;

   label1.Text = string.Format("{0:HH:mm:ss}", elapsed);
}
Run Code Online (Sandbox Code Playgroud)


Rei*_*ica 5

最好是使用 TimeSpan 和 DateTime 正如其他人所说。但是,如果您想继续使用当前方法,请将格式字符串更改为:

string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds)
Run Code Online (Sandbox Code Playgroud)

00格式将导致始终打印两位数字,甚至零。