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


Question

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;
}
1
75
2/9/2009 2:41:45 PM

Accepted Answer

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.

203
6/10/2013 11:11:50 AM

should be

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

note the total days otherwise you'll get werid behaviour


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon