Josh
Josh

Reputation: 1901

Stopwatch that counts down in C#

I've seen variations of this by googling it but I have a windows form with a timer control, three textboxes (hour, minute, second) and based on a button being clicked, I want to count down from 2 hours. So right after clicking textbox1 (hour) will be 1, textBox2 (minute) will be 59, textBox3 (second) will be 59 and they will all continue to count down until all read 0.

Does anyone have some code to share for that?

Many thanks.

Upvotes: 9

Views: 8731

Answers (5)

Eton B.
Eton B.

Reputation: 6281

This tutorial explains very well what you're trying to achieve.

How To Create A Countdown Timer Application Using C# And WinForms
archive.today / archive.org

It gives you the option to count down from any given time, not just 2 hours. Of course, you can just set it to 2 hours if it's the only thing you need.

Upvotes: 0

Justin
Justin

Reputation: 4072

Sorry this might not be the exact answer, but you will need to use a timespan to achieve this.

DateTime now = DateTime.Now;

// get the time elapsed since we started the test
// start date was set somewhere else before this code is called
TimeSpan span = now - _startDate;

// format the time left
String timeleft = span.Hours > 0 ? String.Format( "Time Left - {0}:{1:D2}:{2:D2}", span.Hours, span.Minutes, span.Seconds ) : String.Format( "Time Left - {0:D2}:{1:D2}", span.Minutes, span.Seconds );

Upvotes: 0

Paul Sasik
Paul Sasik

Reputation: 81469

Here is a Cope Project article and project that's in the neighborhood of what you want. Might even meet your needs outright if your needs are flexible.

Upvotes: 0

codymanix
codymanix

Reputation: 29490

You can use the TimeSpan class. Initialize of to 2 hours. If you start the Timer get the current timer. Then with a Timer object refresh your display every second. Simply get the current Time. So the remaining time is:

TimeSpan remaining = twoHoursTimespan - (CurrentTime - StartTime);

Upvotes: 5

Nicholas Hill
Nicholas Hill

Reputation: 221

Extract the components from a TimeSpan. Record the current time and date as soon as the button is clicked, and store that in a variable. Then, every second your timer should calculate the duration since the start time.

IE: DateTime result = DateTime.Now.Subtract(StartingTime);

Then, use the parts of the resulting TimeSpan to populate the fields.

IE: int Hour = result.Hour; (or something like that).

Addendum: Don't count down manually every second, because this is likely to cause the countdown to be inaccurate.

Upvotes: 3

Related Questions