DateTime.Compare how to check if a date is less than 30 days old?
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;
}
回答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.
回答2
should be
matchFound = (expiryDate - DateTime.Now).TotalDays < 30;
note the total days otherwise you'll get werid behaviour

浙公网安备 33010602011771号