KTOV
KTOV

Reputation: 704

Make timer decrement actual seconds

I have this code:

public void startSpinTimer()
{
  spinTimer = new DispatcherTimer();
  spinTimer.Tick += spinTimer_Tick;
  spinTimer.Interval = new TimeSpan(0, 0, 0, 1);
  spinTimer.Start();
}

void spinTimer_Tick(object sender, object e)
{
  spinTime--;
  spinnerTimer_txtBlock.Text = spinTime.ToString();
}

The spinTime variable is 6 in this instance. I'm trying to make the 6 represent hours so it'll be displayed as 06:00:00 and then every time the timer ticks it'll take a second away making the 06:00:00 change to 05:59:59 then 05:59:58 and so on..

I've tried to convert the spinTime to a DateTime variable however it doesn't work, it looks like I'm not going down the right path to achieve what I'm trying to do.

Does anyone have any idea what I am doing wrong?

Thanks

Upvotes: 1

Views: 1974

Answers (3)

D Stanley
D Stanley

Reputation: 152566

Rather than using an integer, I would use a DateTime that stores the current time + 6 hours, and compute the difference between the current time and the "end" time:

// right before starting timer
DateTime endTime = DateTime.Now.AddHours(6);

// in the `Tick` event:
spinnerTimer_txtBlock.Text = (endTime - DateTime.Now).ToString("hh\\:mm\\:ss");

Upvotes: 2

MikeH
MikeH

Reputation: 4395

Using a timer to "tick off seconds" is unreliable. You can't guarantee that the tick will occur exactly every 1 second. Instead I suggest the following:

DateTime start = DateTime.Now; //On the start of the timer store the current time
TimeSpan spinTime = new TimeSpan (6,0,0); //Time to spin

On every tick evaluate the difference between the current time and the start time:

TimeSpan delta = DateTime.Now-start; //Time elapsed since start
TimeSpan timeRemaining = spinTime - delta; //Time remaining

This way you ensure that you're not depending on the timer to keep track of an accurate time. Additionally, you can decrease the length of your tick to increase accuracy.

Upvotes: 1

Filip Herudek
Filip Herudek

Reputation: 76

I assume that spinTime is TimeSpan type. You can use this to decrease of a second.

            spinTime = spinTime.Subtract(TimeSpan.FromSeconds(1));

Upvotes: 5

Related Questions