Home > Back-end >  Simple countdown timer C# showing Minutes and Seconds - already have minutes
Simple countdown timer C# showing Minutes and Seconds - already have minutes

Time:04-22

I have a Windows form with a simple countdown timer to show viewers how much time is left in a motor race. It works for showing how many minutes are left, but I need it to show how many minutes and seconds are left.

The user can decide whether to show the time or not (as a label in front of a picturebox), and user can start/stop/reset/add or subtract minutes (all user entry is in minutes).

I would appreciate it if someone could give me a pointer on how to format the time remaining to show as 000:00 (ie mmm:ss) and to count down in seconds.

This is what I have so far:

int timeleft = 10;
private void timer1_Tick(object sender, EventArgs e)
{
    if (timeleft > 0)
    {
        timeleft = timeleft - 1;
        label3.Text = timeleft   " Mins";
    }
    else
    {
        timer1.Stop();
        label3.Text = "Time Up";
    }
}

private void button26_Click(object sender, EventArgs e)
{
    timer1.Start();
}

private void button27_Click(object sender, EventArgs e)
{
    timer1.Stop();
}

private void button32_Click(object sender, EventArgs e)
{
    timer1.Stop();
    timeleft = 20;
    label3.Text = timeleft   " Mins";
}

private void button28_Click(object sender, EventArgs e)
{
    timeleft = timeleft   1;
    label3.Text = timeleft.ToString()   " Mins";
}

private void button30_Click(object sender, EventArgs e)
{
    timeleft = timeleft - 1;
    label3.Text = timeleft.ToString()   " Mins";
}

private void button7_Click(object sender, EventArgs e)
{
    timeleft = timeleft   10;
    label3.Text = timeleft.ToString()   " Mins";
}

private void button29_Click(object sender, EventArgs e)
{
    label3.BringToFront();
}

CodePudding user response:

You should be using a TimeSpan to describe the time left. This would allow you to format the time using custom format strings. I.e.

timeleft = TimeSpan.FromMinutes(20);
label3.Text = timeLeft.ToString("mm\\:ss");

You could also create an additional extension method that prints either minutes or seconds, depending on the remaining time. I.e. if more than one minute, show only minutes, otherwise show seconds. Or show both minutes and seconds if less than 5 minutes but more than 1 minute remaining.

  • Related