Search code examples
c#timercountdown

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 i.e. 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..");
        }
    }

Solution

  • 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);