JAR
JAR

Reputation: 23

C# Visual Studio Increment Timer

I want to create an increment button of 10s for a countdown timer (00:00:00). When the increment button is clicked 6 times and gets to 00:00:60 it needs to pass over to 00:01:00 etc.

Currently have (I can do the timer, just need help with the initial increment):

private void button1_Click_1(object sender, EventArgs e)
{
    int counter = int.Parse(label4.Text);
    counter=counter+10;
    label4.Text = counter.ToString();

Upvotes: 2

Views: 230

Answers (2)

Steve
Steve

Reputation: 216273

You can use a TimeSpan in this way:

(I am assuming that your initial text for the label is "00:00:50")

TimeSpan ts = TimeSpan.Parse(label4.Text);
label4.Text = ts.Add(TimeSpan.FromSeconds(10)).ToString();

EDIT

If you want to check if you have reached the limit of 2 hours you can split the code above in multiple lines

TimeSpan ts = TimeSpan.Parse(label4.Text);
if(ts.Hours == 2)
   label4.Text = "00:00:00"
else
   label4.Text = ts.Add(TimeSpan.FromSeconds(10)).ToString();

Upvotes: 4

MetaColon
MetaColon

Reputation: 2923

That's the reason for modulo existing. You could get the minutes like that:

int hours = counter % 60;

The seconds would have to be changed then as well:

int seconds = (int)(counter / 60);

It's the same for hours.

If you want to know more about Modulo or want to know what it does, take a look at this: https://en.wikipedia.org/wiki/Modulo_operation.

Upvotes: 0

Related Questions