Why datetime cannot compare?

5YrsLaterDBA picture 5YrsLaterDBA · Apr 28, 2010 · Viewed 25.6k times · Source

my C# unit test has the following statement:

Assert.AreEqual(logoutTime, log.First().Timestamp);

Why it is failed with following information:

Assert.AreEqual failed. Expected:<4/28/2010 2:30:37 PM>. Actual:<4/28/2010 2:30:37 PM>.

Are they not the same?

Update:

Use this if you only care to second:

Assert.AreEqual(logoutTime.ToString(), log.First().Timestamp.ToString());

Answer

Dinah picture Dinah · Apr 28, 2010

Have you verified that the number of ticks/milliseconds are equal?

If you do DateTime.Now() twice back to back, they will appear to be the same number down to the minute and probably even down to the second, but they will often vary by ticks. If you want to check equality only to the minute, compare each DateTime only to that degree. For information on rounding DateTimes, see here


A note about resolution:

The Now property is frequently used to measure performance. However, because of its low resolution, it is not suitable for use as a benchmarking tool. A better alternative is to use the Stopwatch class.