tags:

views:

5555

answers:

9

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;
}
A: 

No, the Compare function will return either 1, 0, or -1. 0 when the two values are equal, -1 and 1 mean less than and greater than, I believe in that order, but I often mix them up.

Timothy Carter
+21  A: 

Am I using DateTime Compare correctly?

No. Compare only offers information about the relative position of two data: less, equal or greater. What you want is something like this:

if ((expiryDate - DateTime.Now).Days < 30)
    matchFound = true;

This subtracts two DateTimes. The result is a TimeSpan object which has a Days property.

Additionally, the conditional can written directly as:

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

No if needed.

Konrad Rudolph
Should be allowed to give you 2+ ;) one for the answer and one for the short way to express it
CheGueVerra
Uh … I just made my answer longer so feel free to subtract one imaginary vote. ;-)
Konrad Rudolph
A: 

No you are not using it correctly.

See here for details.

DateTime t1 = new DateTime(100);
DateTime t2 = new DateTime(20);

if (DateTime.Compare(t1, t2) >  0) Console.WriteLine("t1 > t2"); 
if (DateTime.Compare(t1, t2) == 0) Console.WriteLine("t1 == t2"); 
if (DateTime.Compare(t1, t2) <  0) Console.WriteLine("t1 < t2");
David Basarab
A: 

Try this instead

if ( (expiryDate - DateTime.Now ).TotalDays < 30 ) { 
  matchFound = true;
}
JaredPar
Hmm, you need to either invert the order of your dates or take the absolute value, unless the expiration date is already passed.
Konrad Rudolph
@Konrad, yeah, I read the question wrong. Corrected
JaredPar
A: 

What you want to do is subtract the two DateTimes (expiryDate and DateTime.Now). This will return an object of type TimeSpan. The TimeSpan has a property "Days". Compare that number to 30 for your answer.

GWLlosa
A: 

No it's not correct, try this :

DateTime expiryDate = DateTime.Now.AddDays(-31);
if (DateTime.Compare(expiryDate, DateTime.Now.AddDays(-30)) < 1)
{
    matchFound = true;
}
Canavar
+1  A: 

Compare returns 1, 0, -1 for greater, equal, less than. You want:

    if (DateTime.Compare(expiryDate, DateTime.Now.AddDays(30)) <= 0) 
    { 
        bool matchFound = true;
    }
Mitch Wheat
+1  A: 

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...

haqwin
A: 

should be

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

note the total days otherwise you'll get werid behaviour

Luke