0

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..");
        }
    }
panman
  • 75
  • 15
  • 2
    Please read [ask]. Your post is far from minimal to explain your problem. Create a MCVE. – Amit Dec 13 '15 at 19:02
  • Use days with hours instead of just hours – Techidiot Dec 13 '15 at 19:03
  • Sunilar -http://stackoverflow.com/questions/11875403/android-countdown-timer-to-date for reference – Techidiot Dec 13 '15 at 19:05
  • Actually the problem is that label6 displays the countdown. I want countdown to start form 56 hours and decreasing . But the countdown timer does not show countdown from 56 hours(56:00:00) instead it starts from (24:00:00) don't know why that is happening – panman Dec 13 '15 at 19:05

2 Answers2

0

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.

Jose Luis
  • 994
  • 1
  • 8
  • 22
0

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);
Gian Paolo
  • 4,161
  • 4
  • 16
  • 34