Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking TimeSpan

Tags:

c#

.net

.net-3.5

I have a method that queries active directory, and returns the value of the Last Password Reset to a local variable. I am trying to compare that value to the current date and time, and check if it's been less than 24 hours. I think I'm close, but can't seem to get this to work.

Thanks, Jason

string passwordLastSet = string.Empty;
passwordLastSet = DateTime.FromFileTime((Int64)(result.Properties["PwdLastSet"][0])).ToString();  
public string lastReset(DateTime pwordLastReset)
{
    if (DateTime.Now.AddHours(24) <= passwordLastSet)
    {
        return "try again later";
    }
    else
    {
        return "all is good";
    }
}
like image 973
Jason Avatar asked Feb 10 '11 17:02

Jason


2 Answers

I am trying to compare that value to the current date and time, and check if it's been less than 24 hours.

This code almost writes itself.

DateTime timeOfLastPasswordReset = // get time of last password reset
DateTime now = DateTime.Now;
TimeSpan difference = now.Subtract(timeOfLastPasswordReset);
if(difference < TimeSpan.FromHours(24)) {
    // password was reset less than twenty-four hours ago
}
else {
    // password was reset no less than twenty-four hours ago
}

Note how the code reads exactly as you specified in English.

like image 190
jason Avatar answered Sep 26 '22 01:09

jason


This:

 if (DateTime.Now.AddHours(24) <= passwordLastSet)

should be

   if (DateTime.Now <= passwordLastSet.AddHours(24))
like image 26
BrokenGlass Avatar answered Sep 27 '22 01:09

BrokenGlass