Stopwatch counting in C #

I have seen variations of this by googling, but I have a timer window shape, three text fields (hour, minute, second) and based on the click of a button, I want to recount 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 counting until everyone reads 0.

Does anyone have any code to share?

Many thanks.

+7
c #
source share
5 answers

You can use the TimeSpan class. Initialization up to 2 hours. If you start the timer, get the current timer. Then, using the Timer object, refresh your screen every second. Just get the current Time. So, the remaining time:

Remaining TimeSpan = two hours of time - (CurrentTime - StartTime);

+3
source share

Remove components from TimeSpan. Record the current time and date as soon as the button is pressed, and save it in a variable. Then, every second, your timer should calculate the duration from the moment it starts.

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

Then use the parts of the resulting TimeSpan to fill in the fields.

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

Addition: do not manually calculate every second, because this can lead to an incorrect countdown.

+3
source share

This tutorial explains very well what you are trying to achieve.

http://www.dreamincode.net/forums/topic/57482-countdown-timer/

It gives you the opportunity to countdown from any given time, and not just for 2 hours. Of course, you can just set it to 2 hours if that is the only thing you need.

0
source share

Here is the Cope Project article and project , which is next to what you want. You can even meet your needs if your needs are flexible.

0
source share

Sorry, this may not be the exact answer, but for this you will need to use a time period.

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 ); 
0
source share

All Articles