Bronzato
Bronzato

Reputation: 9342

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);

Thanks.

Upvotes: 2

Views: 12207

Answers (4)

Evan L
Evan L

Reputation: 3855

Why not just parse the DateTime to your furthest desired precision (I'm assuming you want yyyy-MM-dd HH:mm:ss). And then compare them. I realize this is a bit long winded but an answer none-the-less.

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

if (DateTime.Compare(DateTime.ParseExact(dte1.ToString("yyyy-MM-dd HH:mm:ss"), 
                                                       "yyyy-MM-dd HH:mm:ss", 
                                                        null), 
                     DateTime.ParseExact(dte2.ToString("yyyy-MM-dd HH:mm:ss"), 
                                                       "yyyy-MM-dd HH:mm:ss", 
                                                        null)) != 0)
{
    throw new HttpRequestException(ExceptionMessages.CONCURRENCY_UPDATE);
}

Sorry for the bad formatting, just trying to minimize the horizontal scroll. This avoids the problem that the marked answer presents.

Upvotes: 3

pitermarx
pitermarx

Reputation: 928

I made this extension method

public static bool IsEqual(this DateTime start, DateTime end, long toleranceInMilliseconds = -1)
{
    if (toleranceInMilliseconds < 0)
       toleranceInMilliseconds = 0;

    return Math.Abs((start - end).TotalMilliseconds) < toleranceInMilliseconds;
}

Upvotes: 4

catfood
catfood

Reputation: 4331

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.");
}

Upvotes: 8

gleng
gleng

Reputation: 6304

Before you compare the two, just do something like the following:

firstDateTime = firstDateTime.AddMilliseconds(-firstDateTime.Millisecond);
secondDateTime = secondDateTime.AddMilliseconds(-secondDateTime.Millisecond);

Upvotes: 2

Related Questions