其他分享
首页 > 其他分享> > 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?

作者:互联网

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

 

 

 

标签:Compare,old,less,30,TotalDays,DateTime,expiryDate,than
来源: https://www.cnblogs.com/chucklu/p/16088026.html