Jordan1993
Jordan1993

Reputation: 822

How to check if a date occurred more than 1 year ago in C#?

I have the following code:

var consentedOnDate = GetConsentedOn(consent.Id);
var declinedOnDate = GetConsentDeclinedOn(consent.Id);
                
var userHasGivenConsentLessThan1YearAgo = consentedOnDate != null && (consentedOnDate.Value - DateTime.Now.Date).TotalDays < -365;
var userHasDeclinedConsentLessThan1YearAgo = declinedOnDate != null && (declinedOnDate.Value - DateTime.Now.Date).TotalDays < -365;

I want the userHasGivenConsentLessThan1YearAgo and userHasDeclinedConsentLessThan1YearAgo variables to be true if the consentedOnDate and declinedOnDate are OVER 1 year old from today, but the logic as I has it doesn't seem to be working - have I got this correct? By not working I mean that it says true when should be false, and vice versa.

Upvotes: 2

Views: 2582

Answers (1)

Chrᴉz remembers Monica
Chrᴉz remembers Monica

Reputation: 1904

You can simplify your code and use built-in DateTime-methods:

var consentDate = GetConsentedOn(consent.Id);
var consentDeclinedDate = GetConsentDeclinedOn(consent.Id);
                
var isConsentMoreThan1YearAgo = consentDate  < DateTime.Today.AddYears(-1);
var hasDeclinedMoreThan1YearAgo = consentDeclinedDate < DateTime.Today.AddYears(-1);

If today is the 1st of October 2020, this will return true if the variable consentDate is earlier than 01.10.2020 00:00:00 (date and time) and else false. False cases would include 01.10.2020 00:00:00, 20.10.2020 00:00:00 and consentDate being null.

Please also note the new names of the variables, i.e. booleans beginning with "is" or "has".

Upvotes: 2

Related Questions