简体   繁体   English

如何建立倒数计时器

[英]how to create a countdown timer

I want to create a countdown timer of say 56 hours that will display countdown dynamically on my app.It should also be persistent between restarts ie if before restart my timer shows that 3 hours passed then after restart it should continue from 3 hours, not reset .I used this method where I will write current date + 56 hours to a text file and then use it for reference, but the problem is that the countdown displayed on "label6" doesn't go above 24 hours (I want it to show countdown form 56:00:00 then up to 00:00:00) If there is any other way to do it, please share.. thanks 我想创建一个说56小时的倒计时计时器,该计时器将在我的应用程序上动态显示倒计时。两次重启之间也应该保持不变,即如果重启之前我的计时器显示经过了3个小时,那么重启后应该从3个小时开始而不是重置。我使用了这种方法,将当前日期+ 56小时写入文本文件,然后将其用作参考,但是问题是“ label6”上显示的倒数不会超过24小时(我希望它显示倒计时表格56:00:00,然后最多00:00:00)如果还有其他方法,请分享..谢谢

my code: 我的代码:

public void timer()
    {
        string path1 = userdir + username + app + file;

        string triggerfile = path1;
        if (!File.Exists(triggerfile))
        {
            string ss = (DateTime.Now.AddHours(56).ToString());

            System.IO.File.WriteAllText(triggerfile, ss);
        }
        using (StreamReader sr = File.OpenText(triggerfile))
        {
            triggerdate = DateTime.Parse(sr.ReadToEnd());
        }
        var st = triggerdate;

        var timer = (new Timer() { Interval = 1000 });
        timer.Tick += (obj, args) => label6.Text = (TimeSpan.FromSeconds(20) - (st - DateTime.Now)).ToString("hh\\:mm\\:ss");
        timer.Enabled = true;

        if (DateTime.Now >= triggerdate)
        {

            label17.Text = "Times up";
            MessageBox.Show("YOU ARE PAST YOUR TRIAL HOURS..");
        }
    }

It could be something like this: 可能是这样的:

    var currentTime = (triggerdate.Subtract(DateTime.Now));
    string remainingTime = "" + (currentTime.Days*24 + currentTime.Hours) + ":" + currentTime.Minutes + ":" + currentTime.Seconds);

    var timer = (new Timer() { Interval = 1000 });
    timer.Tick += (obj, args) => label6.Text = remainingTime;
    timer.Enabled = true;

When you add 56 hours to a date, is the same to add 2 days and 8 hours. 当您向日期添加56小时时,添加2天8小时是相同的。 You have to convert the days of a DateTime to hours, and add this hours to the hours of the DateTime, to get the total hours. 您必须将DateTime的日期转换为小时,然后将此小时添加到DateTime的小时中,以获取总小时数。

I hope this help to you. 希望对您有帮助。

you can use the TotalHours property of your TimeSpan 您可以使用TimeSpanTotalHours属性

TimeSpan remaining = ... ; // compute remaining time
string label = string.Format("{0}:{1:mm\\:ss}", (int) remaining.TotalHours, remaining);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM