Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

datetime - 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 :)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...