Click here to Skip to main content
15,894,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I've created a countdown timer whose code looks like:
C#
protected void Timer1_Tick(object sender, EventArgs e)
    {
        try
        {
            dt1 = dt1.AddSeconds(1);
Label4.Text = (TimeSpan.FromHours(2D) - TimeSpan.FromSeconds(dt1.Second)).ToString("hh\\:mm\\:ss");
}
}


But the above code worked for only 1 min. in reverse order then repetition goes on again. Can it be possible to create timer in reverse order for 1/2 hours.

Please provide the snippet

Thanks a lot in advance

What I have tried:

The above code I tried and the output comes like 01:59:59, 01:59:58 and so on.
Posted
Updated 11-Nov-16 6:29am

1 solution

Instead of using a DateTime and changing it, take the current time when you start teh timer, and set a target time:
C#
private DateTime target;
...
target = DateTime.Now.AddMinutes(30);
Timer1.Start();

Then, in your Tick handler, check the difference:
C#
void Timer1_Tick(object sender, EventArgs e)
    {
    TimeSpan diff = target - DateTime.Now;
    if (diff.TotalSeconds <= 0)
        {
        myTextBox.Text = "Done!";
        Timer1.Stop();
        }
    else
        {
        myTextBox.Text = ((int) diff.TotalSeconds).ToString();
        }
    }
That way, it will work with almost any offset, and be a lot more accurate.
 
Share this answer
 
Comments
binadi007 11-Nov-16 13:29pm    
Hi OriginallGriff,
I've some doubts,
1) Where to call "target = DateTime.Now.AddMinutes(30);" (I'm caling Timer1.Start() from aspx file i.e by <asp:timer> tag)
2) I need the remaining time in hh:mm:ss format not in seconds that is mentioned by myTextBox.Text = ((int) diff.TotalSeconds).ToString();

Thanks a lot for help
OriginalGriff 11-Nov-16 14:02pm    
Right - don't do that in C# at all, don't even put the timer there.
For websites, you want the timer to be handled at the client, not the server: so do your countdown in Javascript, not C#.
Build a Countdown Timer in Just 18 Lines of JavaScript[^]
binadi007 11-Nov-16 21:56pm    
yes you are right and I'll implement it as well, but for the time being can u provide the answer of these 2 questions i.e:-
1) Where to call "target = DateTime.Now.AddMinutes(30);" (I'm caling Timer1.Start() from aspx file i.e by <asp:timer> tag)
2) I need the remaining time in hh:mm:ss format not in seconds that is mentioned by myTextBox.Text = ((int) diff.TotalSeconds).ToString();

thanks
OriginalGriff 12-Nov-16 4:44am    
No - because it's completely pointless as it's on the wrong side.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900