Search code examples
c#datetimecomparison

DateTime Comparison Precision


I'm doing DateTime comparison but I don't want to do comparison at second, millisecond and ticks level. What's the most elegant way?

If I simply compare the DateTime, then they are seldom equal due to ticks differences.


Solution

  • What about using a timespan.

    if (Math.Truncate((A - B).TotalMinutes) == 0)
    {
        //There is less than one minute between them
    }
    

    Probably not the most elegant way, but it allows for cases which are one second apart and yet have different days/hours/minutes parts such as going over midnight.

    Edit: it occured to me that the truncate is unecessary...

    if (Math.Abs((A - B).TotalMinutes) < 1)
    {
        //There is less than one minute between them
    }
    

    Personally I think this is more elegant...