DateTime.Compare how to check if a date is less than 30 days old?

Am I using DateTime Compare correctly?

No. Compare only offers information about the relative position of two dates: less, equal or greater. What you want is something like this:

if ((expiryDate - DateTime.Now).TotalDays < 30)
    matchFound = true;

This subtracts two DateTimes. The result is a TimeSpan object which has a TotalDays property.

Additionally, the conditional can be written directly as:

bool matchFound = (expiryDate - DateTime.Now).TotalDays < 30;

No if needed.

Alternatively, you can avoid naked numbers by using TimeSpan.FromDays:

bool matchFound = (expiryDate - DateTime.Now) < TimeSpan.FromDays(30);

This is slightly more verbose but I generally recommend using the appropriate types, and the appropriate type in this case is a TimeSpan, not an int.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)