D.madushanka
D.madushanka

Reputation: 563

Stop countdown timer in Xamarin forms after a specific day

I am new to C# and needed a countdown timer. I used this code with few modification.

Link

Original code....

DateTime endTime = new DateTime(2018,12,31,0,0,0);
private void button1_Click(object sender, EventArgs e)
{ 
    Timer t = new Timer();
    t.Interval = 500;
    t.Tick +=new EventHandler(t_Tick);
    TimeSpan ts = endTime.Subtract(DateTime.Now);
    label1.Text = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'");
    t.Start();
}

void  t_Tick(object sender, EventArgs e)
{
    TimeSpan ts = endTime.Subtract(DateTime.Now);
    label1.Text = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'");
}

My code....

    DateTime endTime = new DateTime(2018,12,31,0,0,0);
    private void countDownTimer()
    {
        Timer t = new Timer();
        t.Interval = 1000;
        t.Elapsed += new ElapsedEventHandler(t_Tick);
        TimeSpan ts = endTime.Subtract(DateTime.Now);
        cTimer = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'");
        t.Start();
    }

    void t_Tick(object sender, EventArgs e)
    {
        TimeSpan ts = endTime.Subtract(DateTime.Now);
        cTimer = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'");
    }

This is working great and I wanna know how to stop the timer after the countdown. Now it is counting up after the countdown date.

Upvotes: 3

Views: 1613

Answers (1)

Access Denied
Access Denied

Reputation: 9501

You can stop it this way:

DateTime endTime = new DateTime(2018, 11, 21, 12, 31, 0);
public void StartCountDownTimer()
{
   timer = new System.Timers.Timer();
   timer.Interval = 1000;
   timer.Elapsed += t_Tick;
   TimeSpan ts = endTime - DateTime.Now;
   cTimer = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'");
   timer.Start();
}
string cTimer;
System.Timers.Timer timer;
void t_Tick(object sender, EventArgs e)
{
   TimeSpan ts = endTime - DateTime.Now;
   cTimer = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'");
   if ((ts.TotalMilliseconds < 0) || (ts.TotalMilliseconds < 1000))
   {
      timer.Stop();
   }
}

Upvotes: 1

Related Questions