Compare() method in C# is used for comparison of two DateTime instances. It returns an integer value, <0 − If date1 is earlier than date2. 0 − If date1 is the same as date2.
Use the datetime Module and the < / > Operator to Compare Two Dates in Python. datetime and simple comparison operators < or > can be used to compare two dates. The datetime module provides the timedelta method to manipulate dates and times.
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 DateTime
s. 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.
should be
matchFound = (expiryDate - DateTime.Now).TotalDays < 30;
note the total days otherwise you'll get werid behaviour
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...
Try this instead
if ( (expiryDate - DateTime.Now ).TotalDays < 30 ) {
matchFound = true;
}
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;
}
This will give you accurate result :
if ((expiryDate.Date - DateTime.Now.Date).Days < 30)
matchFound = true;
Compare is unnecessary, Days / TotalDays are unnecessary.
All you need is
if (expireDate < DateTime.Now) {
// has expired
} else {
// not expired
}
note this will work if you decide to use minutes or months or even years as your expiry criteria.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With