Search code examples
c#stringtimercountdowncountdowntimer

Countdown Timer Skipping Time in C#


I Have This in C#

private void counter_Tick(object sender, EventArgs e)
    {
        Time.Text = String.Format("{0:000}", Hour) + ":" + String.Format("{0:00}", Minute) + ":" + String.Format("{0:00}", Second);
        if (Second != 00)
        {
            Second = Second - 1;
        }
        else if (Minute != 00)
        {
            Minute = Minute - 1;
            Second = 59;
        }
        else if (Hour != 00)
        {
            Hour = Hour - 1;
            Minute = 59;
        }
        else
        {
            counter.Stop();
            Time.ForeColor = Color.Red;
        }
    }

Which Does work but when it gets to minus an hour to add to minutes, it goes from 00 minutes to 58 minutes instead of 59

EG.

From: 001:00:00
To:   000:58:59

And is there a better way to make a countdown timer that does something when it hits 000:00:00???


Solution

  • Well let's see what happens when the time is 10:00:00.

    1. Subtract one hour: 09:00:00.
    2. Set minutes to 59: 09:59:00.

    If you notice the time is off by one minute (10:00:00 - 09:59:00 = 00:01:00). The solution is to set the seconds to 59 also. So now our code is.

    // ...
    else if (Hour != 00)
    {
        Hour = Hour - 1;
        Minute = 59;
        Second = 59;
    }
    // ...