0

I have a AJAX C# ASP.NET control and it works properly (counts down from 2 hours from current time only when the datetime is hardcoded. I would like to pass in dates as a variable but every time I do so, the timer stops working.

Here's what works...

 protected void Timer1_Tick(object sender, EventArgs e)
    {
        String DateTimeFuture = DateTime.Now.AddHours(2).ToString();
        DateTime NeededByDateTime = DateTime.Parse("03/18/2017 10:00:00 AM");
        TimeSpan time1 = new TimeSpan();
        time1 = NeededByDateTime - DateTime.Now;
        if ((time1.Hours == 0) && (time1.Minutes == 0) && (time1.Seconds == 0))
        {
            Label1.Text = "Time Expired!";
            //Return article to results
        }
        else
        {
            string countDown = string.Format("{0} Days, {1} Hours, {2} Minutes, {3} Seconds til launch.", time1.Days, time1.Hours, time1.Minutes, time1.Seconds);
            Label1.Text = countDown.ToString();
        }

    }

Here's what doesn't work...

protected void Timer1_Tick(object sender, EventArgs e)
    {
        String DateTimeFuture = DateTime.Now.AddHours(2).ToString();
        DateTime NeededByDateTime = DateTime.Parse(DateTimeFuture);
        TimeSpan time1 = new TimeSpan();
        time1 = NeededByDateTime - DateTime.Now;
        if ((time1.Hours == 0) && (time1.Minutes == 0) && (time1.Seconds == 0))
        {
            Label1.Text = "Time Expired!";
        }
        else
        {
            string countDown = string.Format("{0} Days, {1} Hours, {2} Minutes, {3} Seconds til launch.", time1.Days, time1.Hours, time1.Minutes, time1.Seconds);
            Label1.Text = countDown.ToString();
        }

    }

Any ideas as to why it isn't working for the second piece of code?

UPDATE:

If you would like to try to get the example working for your environment, you'll need the following code in your page.

 <form method="post" runat="server" action="Page.aspx">
                <asp:ScriptManager ID="ScriptManager1" runat="server" />

            <asp:UpdatePanel ID="UpdatePanel1" Visible="true" runat="server" >
                <ContentTemplate>
                    <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
                    </asp:Timer>
                    <asp:Label ID="Label1" runat="server"></asp:Label>
                </ContentTemplate>
            </asp:UpdatePanel>
</form>
6
  • In second example the result of contentNeededByDateTime - DateTime.Now; is always about 2 hours. Commented Mar 18, 2017 at 12:53
  • It counts down using the ajax control with seconds in ticks. They are both identical code except for the time variable. DateTime.Parse gives date and time as far as I know. Commented Mar 18, 2017 at 12:55
  • Every time your timer ticks DateTimeFuture is set to a point 2 hours ahead from now. Commented Mar 18, 2017 at 12:57
  • So should I make it a const value or what do you suggest? I'd like to pass it in as a static value Commented Mar 18, 2017 at 12:59
  • 1
    You can store it in a session or view state. Commented Mar 18, 2017 at 13:00

2 Answers 2

2

What exactly doesn't work? Does it throw an exception. What is the value of the contentNeededByDateTime variable after you parse the date? Is it correct?

There may be an issue with the current culture. So to make sure that you pass the correct format to the parser, instead of ToString(), use some explicit formatting: http://www.csharp-examples.net/string-format-datetime/

I assume this is just a test code and you're going to pass the variable as a string parameter. So you just need to make sure that you pass the value in the correct format.

UPDATE

Based on the comments bellow, I understand the issue a little bit more. You can't declare the date inside the method because it gets updated every time this method is called which is probably every second. If you want to be able to have a countdown for each user. Get the date and time when a user request the page with the timer and save it to Session:

Session["NeededByDateTime"] = DateTime.Now.AddHours(2);

And then the method would look like this:

protected void Timer1_Tick(object sender, EventArgs e)
{
    //for the sake of simplicity but you should check if it exists first
    DateTime NeededByDateTime = (DateTime)Session["NeededByDateTime"]; 

    time1 = NeededByDateTime - DateTime.Now;
    if ((time1.Hours == 0) && (time1.Minutes == 0) && (time1.Seconds == 0))
    {
        Label1.Text = "Time Expired!";
    }
    else
    {
        string countDown = string.Format("{0} Days, {1} Hours, {2} Minutes, {3} Seconds til launch.", time1.Days, time1.Hours, time1.Minutes, time1.Seconds);
        Label1.Text = countDown.ToString();
    }

}
Sign up to request clarification or add additional context in comments.

7 Comments

It stays stuck at 2 hours when the variable is introduced
Oh, I see. I thought it doesn't parse the date. That's an event that is triggered each let's say second? In that case you need to get rid of the first line String DateTimeFuture = DateTime.Now.AddHours(2).ToString(); because each time it hits this method, it gets the current time and, sets the timer to 2 hours ahead of the current time.
But that is the point I want to countdown from 2 hours from the point someone hits the page for now.
Then get the correct date when somebody requests the page, save it to Session and in this Timer1_Tick method, get the date from Session.
Your solution also stays stuck at: 0 Days, 1 Hours, 59 Minutes, 59 Seconds til launch and does not count down. It is weird that it only likes hardcoded datetime values to do the countdown
|
0

Your example won't work, since time1 is always going to be equal to 2 hours every time the Timer calls the Tick method.

protected void Timer1_Tick(object sender, EventArgs e)
{
    String DateTimeFuture = DateTime.Now.AddHours(2).ToString(); // NOW + 2 HOURS
    DateTime NeededByDateTime = DateTime.Parse(DateTimeFuture);
    TimeSpan time1 = new TimeSpan();
    time1 = NeededByDateTime - DateTime.Now; // NOW + 2 HOURS - NOW = 2 HOURS
    if ((time1.Hours == 0) && (time1.Minutes == 0) && (time1.Seconds == 0))
    {
        Label1.Text = "Time Expired!";
    }
    else
    {
        string countDown = string.Format("{0} Days, {1} Hours, {2} Minutes, {3} Seconds til launch.", time1.Days, time1.Hours, time1.Minutes, time1.Seconds);
        Label1.Text = countDown.ToString();
    }
}

You should declare the NeededByDateTime variable outside the Tick method, so it remains constant and not updated on every tick.

private DateTime NeededByDateTime = DateTime.Now.AddHours(2); //.., or whatever you want 

protected void Timer1_Tick(object sender, EventArgs e)
{
    TimeSpan time1 = NeededByDateTime - DateTime.Now;
    if ((time1.Hours == 0) && (time1.Minutes == 0) && (time1.Seconds == 0))
    {
        Label1.Text = "Time Expired!";
    }
    else
    {
        string countDown = string.Format("{0} Days, {1} Hours, {2} Minutes, {3} Seconds til launch.", time1.Days, time1.Hours, time1.Minutes, time1.Seconds);
        Label1.Text = countDown.ToString();
    }
}

5 Comments

This solution toggles between a second less then more so it doesn't work.
It should work. Let's say, we set our NeededByDateTime to a date in future. As time passes, the DateTime.Now will get closer and closer to the date specified in NeededByDateTime. When DateTime.Now reaches the date set in NeededByDateTime, time1 (which is the difference between DateTime.Now and NeededByDateTime) will be 0, and that is what you are looking for.
Yes, that is what I am looking for.
Indeed that is what my second example does. The trick is that you set the DateTime outside the Tick method and not inside.
I tried your solution and it stays stuck at 0 Days, 1 Hours, 59 Minutes, 59 Seconds til launch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.