Bronzato Bronzato - 24 days ago 6
ASP.NET (C#) Question

Comparing 2 dates and ignoring milliseconds of difference

I have 2 dates, how can I compare these 2 dates and ignoring milliseconds of difference?

DateTime dte1 = (DateTime)entity.secondDate;
DateTime dte2 = (DateTime)entity.firstDate;

if (DateTime.Compare(dte1, dte2)!=0)
throw new HttpRequestException(ExceptionMessages.CONCURRENCY_UPDATE);


Answer Source

This is the simplest way if we take your question to mean, "How can I compare two DateTime objects and consider them equal if they're less than, e.g., 100 milliseconds apart?"

double diff = if (dte1.Subtract(dte2)).TotalMilliseconds;
if (Math.Abs(diff) < 100)
    Console.WriteLine("It's all good.");