Verifying datetime fluent nhibernate mappings

You have to be careful when comparing date times because it may seem like they are the same but they can vary down to the ticks (100 nanoseconds). It's probably failing because sql server doesn't store the date times that accurately.

You'll need use a custom equality comparer such that you only compare year, month, day, hour, minute and second probably.

Take a look at this article too: Why datetime cannot compare?


I just ran into this while using an in-memory SQLite session. I debugged through it and noticed that the DateTimes' "Milliseconds" and "Kind" properties differed ("Utc" Kind vs. "Unspecified").

My implementation per Cole W's suggestion:

class DateTimeEqualityComparer : IEqualityComparer
{
    private TimeSpan maxDifference;

    public DateTimeEqualityComparer(TimeSpan maxDifference)
    {
        this.maxDifference = maxDifference;
    }

    public bool Equals(object x, object y)
    {
        if (x == null || y == null)
        {
            return false;
        }
        else if (x is DateTime && y is DateTime)
        {
            var dt1 = (DateTime)x;
            var dt2 = (DateTime)y;
            var duration = (dt1 - dt2).Duration();
            return duration < maxDifference;
        }
        return x.Equals(y);
    }

    public int GetHashCode(object obj)
    {
        throw new NotImplementedException();
    }
}

Your specification test becomes something like this:

var maxDifference = TimeSpan.FromSeconds(1);
...
new PersistenceSpecification<Blah>(Session)
    ...
    .CheckProperty(c => c.Created, System.DateTime.Now,
            new DateTimeEqualityComparer(maxDifference))