tags:

views:

110

answers:

3

How do I test if two dates are within a certain tolerance in NUnit?

+1  A: 

Convert your tolerance to Ticks and then use an And constraint. Something like;

long ticks = mydate.Ticks;
long tolerance = 1000;
Assert.That( ticks, Is.LessThan( ticks + tolerance ) & Is.GreaterThan( ticks - tolerance ) );

I would create an extension method or your own Assert to do this though.

Rob Prouse
+1  A: 

Subtract one from the other, which gives you a TimeSpan value, use the TotalXYZ properties (like TotalMilliseconds) to get a value, use Math.Abs on it to convert it to a always-positive value, and check against your tolerance value.

For instance, if they need to be within 10 milliseconds of each other:

if (Math.Abs((dt1 - dt2).TotalMilliseconds) <= 10)
{
    CloseEnough();
}
Lasse V. Karlsen
+2  A: 

You may want to look at the "Within" method that lives off of the Constraint object.

For example:

Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now.AddMilliseconds(1000)).Within(101));

It's usually used to give a tolerance to doubles and floats, but since in the end a DateTime is a double, it might suit your needs.

CubanX