C#C
C#3y ago
The Joker

❔ Help C# countdown timer

I'm creating a countdown timer, I managed to make the minutes and seconds work, however I need it to have hours too but I'm not managing to set the code logic to show the hours, in my case the user type in a textbox the time and click on the button time starts running until it reaches 0, please could someone help me

int time = 0;
        int minutes = 0;
        int seconds = 0;
        int hours = 0;

private void btnStart_Click(object sender, EventArgs e)
        {
           time = Convert.ToInt32(txtTempo.Text);

            if(time >= 60)
            {
                hours = time / 24;
                minutes = time % 60;
                seconds = time % 60;  
            }
            else
            {
                hours = 0;
                minutes = 0;
                seconds = time;
               
            }
            lblTempo.Text = string.Format("{0}:{1}:{2}", hours.ToString().PadLeft(2, '0'), minutes.ToString().PadLeft(2, '0'), seconds.ToString().PadLeft(2, '0'));
            timer1.Enabled = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            seconds--;

            if (hours > 0)
            {
                if (minutes < 0)
                {
                    minutes = 59;
                    hours--;
                    
                    if (minutes > 0)
                    {
                        if (seconds < 0)
                        {
                            seconds = 59;
                            minutes--;
                            
                        }
                    }
                }
            }
            lblTempo.Text = string.Format("{0}:{1}:{2}", hours.ToString().PadLeft(2, '0'), minutes.ToString().PadLeft(2, '0'), seconds.ToString().PadLeft(2, '0'));

            if (hours == 0 && minutes == 0 && seconds == 0)
            {
                timer1.Enabled = false;
            }
        }
image.png
Was this page helpful?