I'm trying to compare two DateTimeOffsets but the DateTimeOffset.Compare() function is not functioning as expected. I have created the example script to demonstrate the issue. In this example I expected the result of comparing dateA and dateB to be zero (The same).
using System;
namespace ComparingDateTimeOffset
{
class Program
{
static void Main(string[] args)
{
DateTimeOffset dateA = DateTimeOffset.Now;
Thread.Sleep(1);
DateTimeOffset dateB = DateTimeOffset.Now;
Console.WriteLine("dateA =" + dateA);
Console.WriteLine("dateB =" + dateB);
Console.WriteLine(DateTimeOffset.Compare(dateA, dateB) == 0
? "dateA and dateB are the same"
: "dateA and dateB are NOT the same");
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
}
The results of the above program are
dateA =17/02/2016 09:09:21 +00:00
dateB =17/02/2016 09:09:21 +00:00
dateA and dateB are NOT the same
Press any key to exit
In the console output it looks like the two dates are equal. But the compare function says the two dates are different. The following code shows that there are a few milliseconds difference between the two dates.
long diff = (long) (dateB - dateA).TotalMilliseconds;
Console.WriteLine("Time differance in milliseconds =" + diff);
To avoid using the DateTimeOffset.Compare function. I have decided to calculate the difference between the dates in seconds and then round to the nearest integer. This seams to work. Can anyone see a disadvantage of using this method?
Console.WriteLine((int)(dateB - dateA).TotalSeconds == 0
? "dateA and dateB are the same"
: "dateA and dateB are NOT the same");