My web page has a timeout of 5 minutes. I want to show the users the count down in minutes and seconds so I want to show something like :
4 minutes and 10 seconds left
I tried to implement below code in order to achieve this:
<asp:Timer ID="Timer1" runat="server" Interval="5000" ontick="Timer1_Tick">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<span style="border:2px; color:tomato">Time Remaining:<asp:Label ID="Label1" runat="server"></asp:Label></span>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick">
</asp:AsyncPostBackTrigger>
</Triggers>
</asp:UpdatePanel>
This is showing the timer, but the time is showing like so:
I want to show the timer as minutes and seconds. How can I achieve that. Below is my .cs page code:
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.Second.ToString();
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Presently, your code-behind is updating Label1 with the second of the current time. What you want is how much time is remaining until five minutes after the user first loaded the page.
Note that if this is simply to display a five-minute countdown, it is certainly simpler and involves far fewer requests to your server to just do so with javascript; see The simplest possible JavaScript countdown timer?
That’s not precisely what you asked for, so let’s take a look at doing it with the asp:Timer and asp:AsyncPostBackTrigger, server-side. To do that, first we’ll need to know what time the user loaded the page. One way you might do that is to set it to the Session (if not already set):
protected void Page_Load(object sender, EventArgs e)
{
if (Session["LoggedInTime"] == null)
Session["LoggedInTime"] = DateTime.Now;
}
Now, in your postback method:
protected void Timer1_Tick(object sender, EventArgs e)
{
// Get the time back from Session
DateTime loggedInTime = Convert.ToDateTime(Session["LoggedInTime"]);
// Add five minutes to calculate the timeout
DateTime outaTime = loggedInTime.AddMinutes(5);
// Subtract the current time to get remaining time
TimeSpan remainingTime = outaTime.Subtract(DateTime.Now);
// Now, we're ready to format our Label...
// First, we probably care if time has already expired
if (remainingTime.Ticks <= 0)
{
Label1.Text = "We're outa time, doc!";
return;
}
// Otherwise, format the Label using our TimeSpan
Label1.Text = $"{remainingTime.Minutes} minutes and {remainingTime.Seconds} seconds left";
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
