Search code examples
c#timercountdowntimer

Timer returning unwanted formatting


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.


Solution

  • 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