Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating countdown to date C#

I want to make a Windows Form Application which only shows a timer as:

xx days xx hours xx minutes xx seconds

  • No option for setting the timer or anything, i want to do that in the code However, the problem is i want it to count down from current time (DateTime.Now) to a specific date. So i end up with the time left as TimeSpan type. I'm now in doubt how to actually display this, so it's actually working, and updating (counting down) Can't seem to find a tutorial that helps me, so i hope i may be able to get some help here :)
like image 617
Treeline Avatar asked Jun 21 '12 20:06

Treeline


1 Answers

You can use a timespan format string and a timer:

DateTime endTime = new DateTime(2013,01,01,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'");
}
like image 123
John Koerner Avatar answered Sep 20 '22 17:09

John Koerner