创建倒计时日期 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11146602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating countdown to date C#
提问by Treelink
I want to make a Windows Form Application which only shows a timer as:
我想制作一个仅显示计时器的 Windows 窗体应用程序:
xx days xx hours xx minutes xx seconds
xx 天 xx 小时 xx 分钟 xx 秒
- 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 :)
- 没有设置计时器或任何东西的选项,我想在代码中这样做但是,问题是我希望它从当前时间(DateTime.Now)倒计时到特定日期。所以我最终将剩下的时间作为 TimeSpan 类型。我现在怀疑如何实际显示它,所以它实际上正在工作,并且正在更新(倒计时)似乎找不到对我有帮助的教程,所以我希望我能在这里得到一些帮助:)
采纳答案by John Koerner
You can use a timespan format stringand 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'");
}
回答by Orn Kristjansson
Use ToDate.Subtract( Now ) then all you have to do is to format the TimeSpan that you get and show it on the form.
使用 ToDate.Subtract( Now ) 然后您所要做的就是格式化您获得的 TimeSpan 并将其显示在表单上。
回答by John Batdorf
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.
您应该能够在 google 上搜索类似的内容并获得数百个结果。 http://channel9.msdn.com/coding4fun/articles/Countdown-to,这是第一个看起来不错的。
回答by Mayank
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);

