C# DateTime comparisons accuracy and rounding

c#, datetime

Solution

The most obvious refactoring would be to remove the duplication:

public static DateTime TruncateToSecond(DateTime original)
{
    return new DateTime(original.Year, original.Month, original.Day,
        original.Hour, original.Minute, original.Second);
}

...
if (TruncateToSecond(userTime) == TruncateToSecond(dbTime))
    ...

You could quite possibly write:

if (userTime.Ticks / TimeSpan.TicksPerSecond
    == dbTime.Ticks / TimeSpan.TicksPerSecond)
   ...

I believe that would work, simply because tick 0 is at the start of a second.

You ought to be careful about the time zone aspect of all of this, of course. You might want to consider using `DateTimeOffset` instead.

Problem

I have two dates. One supplied by the user and accurate to the second and one from the database and accurate to the tick level. This means when they both represent 13/11/2009 17:22:17 (British dates) ``` userTime == dbTime ``` returns false The tick values are 633937297368344183 and 633937297370000000. To fix this I use the code ``` userTime = new DateTime( userTime.Year, userTime.Month, userTime.Day, userTime.Hour, userTime.Minute, userTime.Second); dbTime = new DateTime( dbTime.Year, dbTime.Month, dbTime.Day, dbTime.Hour, dbTime.Minute, dbTime.Second); ``` Is there a more elegant way to achieve this?

Original source