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

I'm trying to work out if an account expires in less than 30 days. Am I using DateTime Compare correctly?

if (DateTime.Compare(expiryDate, now) < 30)

{
     matchFound = true;
}

Solution 1:

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:

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

No if needed.

Solution 2:

should be

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

note the total days otherwise you'll get werid behaviour

Solution 3:

Well I would do it like this instead:

TimeSpan diff = expiryDate - DateTime.Today;
if (diff.Days > 30) 
   matchFound = true;

Compare only responds with an integer indicating weather the first is earlier, same or later...

Solution 4:

Try this instead

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

Solution 5:

Compare returns 1, 0, -1 for greater than, equal to, less than, respectively.

You want:

    if (DateTime.Compare(expiryDate, DateTime.Now.AddDays(30)) <= 0) 
    { 
        bool matchFound = true;
    }