简体   繁体   中英

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

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. 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.

I hope this help to you.

you can use the TotalHours property of your TimeSpan

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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