问题
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 :)
回答1:
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'");
}
回答2:
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);
回答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.
回答4:
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.
来源:https://stackoverflow.com/questions/11146602/creating-countdown-to-date-c-sharp