.NET DateTime.CompareTo Function

The .NET DateTime class has a handy CompareTo function that allows you to compare two DateTime objects and determine which one comes first chronologically. However, I’ve had a bit of trouble lately with interpreting the anticipated results while writing code  and subsequently ended up with several comparison operators that were the opposite of what they should be (I’ll just blame that on my frenetic dyslexia).

Internally, the .NET framework basically subtracts the second date from the first and returns the result:

[sourcecode language=”csharp”]int result = myDateTime.CompareTo(otherDateTime);[/sourcecode]

[sourcecode language=”csharp”]int CompareTo(DateTime myDateTime, DateTime otherDateTime)
{
    long myTicks = myDateTime.Ticks;
    long otherTicks = otherDateTime.Ticks;
    if (myTicks > otherTicks) return 1;
    if (myTicks < otherTicks) return -1;
    else return 0;
}[/sourcecode]

However, attempting to use the function call inline for if statements adds a little complexity to your human buffer (well, at least to mine), so I figured I would put a simple diagram up for getting what you need out of the CompareTo function:

[sourcecode language=”csharp”]int result = Date1.CompareTo(Date2);[/sourcecode]

Situation CompareTo result
Date1 occurs before Date2 -1
Date1 is the same as Date2 0
Date1 occurs after Date2 1
Tagged with: , , ,
Posted in Blurbs