Frekster
Frekster

Reputation: 1148

C# ASP.NET using TimeSpan to restrict hours to log into a website

All,

When a customer logs into my website, I want to show how much time is remaining until the log in link times out.

Using the TimeSpan structure in C#, for some reason, I cannot figure out how to do this task:

TimeSpan diff = (DateTime.Now - orderDate   );

When the customer logs in, I want to show the customer how much time he/she has remaining to log in... "you have 3 hours 33 minutes until this link times out." ... "You have 2 hours 25 minutes until this link times out" etc.

Once 4 hours is hit, when the customer logs in, I am going to redirect him/her to a sorry... the link has timed out page.

So some Psudo code might be...

if (diff.Hours >= 4)
{
response.redirect("log_in_timed_out.aspx");
}
else
{
lblTimeRemaining.Text = "You have " + diff.Hours + " hours and " + diff.Minutes + " minutes remaining until the link times out.";
}

This psudo code makes the hours and minutes count up instead of down to 0. So I log in and it says you have 1 hours 33 minutes, 2 hours 12 minutes, etc. because the TimeSpan is giving me the difference between the two dates. And I want it to count down to 0 such as 3 hours 23 minutes, 2 hours 15 minutes, 1 hour 5 minutes, etc.

How can I show how much time is remaining to the customer each time he/she logs in using the TimeSpan structure and have it count down to 0?

thanks for any feedback.

Upvotes: 0

Views: 1960

Answers (2)

CodesInChaos
CodesInChaos

Reputation: 108840

I recommend keeping all internal DateTimes in UTC, and only convert to local times for display. So I use DateTime.UtcNow instead of DateTime.Now and assume orderTime is in UTC as well.

I first compute the time at which the link expires, and then how much time remains until then.

DateTime expirationTime = orderTime.AddHours(4);
TimeSpan timeRemaining = expirationTime - DateTime.UtcNow;
if(timeRemaining<TimeSpan.Zero)
  Error("Expired");
else
  Write("Remaining {0} hours {1} minutes",timeRemaining.Hours, timeRemaining.Minutes);

For better testability it can be useful not to call DateTime.UtcNow/.Now inline, but to pass in the value. But since I don't know your surrounding code and architecture, I went with the simple approach.

Upvotes: 3

jjchiw
jjchiw

Reputation: 4455

Something like this, since you know that the limit is 4 hours, add the 4 hours to orderDate and then just take the difference between UtcNow, and the condition should change to.....

TimeSpan diff = (orderDate.AddHours(4) - DateTime.UtcNow);


if (diff < TimeSpan.Zero)
{
    response.redirect("log_in_timed_out.aspx");
}
else
{
    lblTimeRemaining.Text = "You have " + diff.Hours + " hours and " + diff.Minutes + " minutes remaining until the link times out.";
}

Upvotes: 1

Related Questions