问题
I created a timer that returns the decreasing time:
public static void timerIdle_Tick(object sender, EventArgs e)
{
if (tempo >= 60)
{
minuto = tempo / 60;
segundo = tempo % 60;
}
else
{
minuto = 0;
segundo = tempo;
}
segundo--;
if (minuto > 0)
{
if (segundo < 0)
{
segundo = 59;
minuto--;
}
}
if (minuto == 0 && segundo == 0)
{
timerIdle.Stop();
timerIdle.Dispose();
dgView.addLinha(2, "config_Teste", "TIMER ACABOU", 0);
}
else
{
tempo = (minuto * 60) + segundo;
string temp = minuto + ":" + segundo;
lblIdle.Text = temp;
dgView.addLinha(2, "config_Teste", temp, 0);
}
}
I get the following result:
...
1:12
1:11
1:10
1:9
1:8
...
0:0
I need to add 0 (Zero) if the minute and second has only one digit:
01:12
01:11
01:10
01:09
01:08
...
00:00
The PadLeft() function does not work because I am using C # 7.3 (.NET Framework 4.7.2).
Please, help-me.
回答1:
So this will format your minutes and seconds into two digits
int minuto = 1;
int segundo= 1;
string temp = string.Format($"{minuto:D2}:{segundo:D2}");
Output:
01:01
回答2:
You just need to set the countdown duration in seconds when you start the Timer
, subtract 1 every second in the Tick
event until you get 0 then stop the timer. Use the TimeSpan.FromSeconds method to format the time string.
//Class variable...
int segundo = 0;
void WhereYouStartTheTimer()
{
segundo = 60; //1 Minute
timerIdle.Interval = 1000; //Fires every 1 second.
timerIdle.Start();
}
private void timerIdle_Tick(object sender, EventArgs e)
{
segundo--;
if (segundo == 0)
{
timerIdle.Stop();
dgView.addLinha(2, "config_Teste", "TIMER ACABOU", 0);
}
else
dgView.addLinha(2, "config_Teste", TimeSpan.FromSeconds(segundo).ToString(@"mm\:ss"), 0);
}
Side note, you don't need to timerIdle.Dispose();
if you create it by the designer. If you create it and subscribe to the Tick
event by code, then you have to remove the handler too then dispose it:
//...
timerIdle.Stop();
timerIdle.Tick -= timerIdle_Tick;
timerIdle.Dispose();
//...
You might want to read Standard TimeSpan format strings for more.
来源:https://stackoverflow.com/questions/62927335/timer-returning-unwanted-formatting