Creating countdown to date C#
Asked Answered
D

4

7

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 :)
Dominiquedominium answered 21/6, 2012 at 20:56 Comment(2)
Which bit of "how to actually display this" is causing you problems?Kassala
If you prefer to work with a DateTime instead of a TimeSpan, you can do new DateTime(yourTimeSpan.Ticks) to get one back. But it sounds like a TimeSpan may actually be easier to use in your case, because it has properties for each of the days, hours, minutes, and seconds labels you have in your form.Lysine
H
10

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'");
}
Hard answered 21/6, 2012 at 21:7 Comment(0)
B
6

following will give you the countdown string

//Get these values however you like.
DateTime daysLeft = DateTime.Parse("1/1/2012 12:00:01 AM");
DateTime startDate = DateTime.Now;

//Calculate countdown timer.
TimeSpan t = daysLeft - startDate;
string countDown = string.Format("{0} Days, {1} Hours, {2} Minutes, {3} Seconds til launch.", t.Days, t.Hours, t.Minutes, t.Seconds);
Biscuit answered 21/6, 2012 at 21:2 Comment(0)
P
3

Use ToDate.Subtract( Now ) then all you have to do is to format the TimeSpan that you get and show it on the form.

Phyla answered 21/6, 2012 at 20:59 Comment(1)
Max value of TimeSpan is Int32.Max which is enogh only for "short time delay". If you have difference more than 24 hours between ToDate and Now - it doesn't work.Pachton
O
0

You should be able to google something like this and get literally hundreds of results. http://channel9.msdn.com/coding4fun/articles/Countdown-to, here's the first one that looked good.

Ope answered 21/6, 2012 at 21:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.