2

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.

Bronzato
  • 9,438
  • 29
  • 120
  • 212
  • 3
    When you say "ignore milliseconds", do you mean that everything is the same except for milliseconds, or that you'd like to see if two DateTimes are within X milliseconds of each other? – Joel Rondeau Jul 15 '13 at 18:28
  • 1
    possible duplicate: http://stackoverflow.com/questions/7028930/ignore-milliseconds-when-comparing-two-datetimes – Steven V Jul 15 '13 at 18:28
  • 1
    Duplicate, but the accepted answer there (and here) is wrong as Jeppe Stig Nielson pointed out. The correct answer is either going to be catfood's here where you compare the different against a fixed tolerance, or Dean Chalk's answer on the other question, where you create brand new DateTime objects and only include year, month, day, hour, minute, second, then you can compare those objects. Depends on whether you want to compare within a margin of error, or if you want to compare by dropping milliseconds. – Joe Enos Jul 15 '13 at 18:56
  • @JoeEnos I also posted an answer to the effect of Dean Chalk's on this thread. Hopefully the OP sees this before he implements code that will not work. – Evan L Jul 15 '13 at 19:00

4 Answers4

8

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.");
}
catfood
  • 4,267
  • 5
  • 29
  • 55
3

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.

Evan L
  • 3,805
  • 1
  • 22
  • 31
  • 3
    A little extra work translating back and forth to strings, rather than dealing with them as numbers. But this should work, assuming you want to drop milliseconds instead of compare to a tolerance. One correction though, should be `HH` instead of `hh`, so you get a 24-hour clock instead of a 12-hour clock. – Joe Enos Jul 15 '13 at 19:00
  • Converting to a `string` and back again to a `DateTime` is unelegant and unnecessary. Joe is right about `HH`; you might Loose a.m./p.m. information otherwise. – Jeppe Stig Nielsen Jul 15 '13 at 19:07
3

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;
}
pitermarx
  • 908
  • 1
  • 9
  • 22
2

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

firstDateTime = firstDateTime.AddMilliseconds(-firstDateTime.Millisecond);
secondDateTime = secondDateTime.AddMilliseconds(-secondDateTime.Millisecond);
gleng
  • 6,185
  • 4
  • 21
  • 35
  • 6
    No! This only removes the whole number of milliseconds. For example if the time of day was `20:33:22.1234567`, after your correction it would be `20:33:22.0004567`. – Jeppe Stig Nielsen Jul 15 '13 at 18:34
  • If the times are "20:51:10.999" and "20:51:11.001" then this would result in a whole second difference (instead of 2 ms). The question is not clear whether that is a problem. – Hans Kesting Jul 15 '13 at 18:54
  • If you want to truncate to a Whole number of milliseconds, one way would be `firstDateTime = new DateTime(firstDateTime.Ticks / TimeSpan.TicksPerMillisecond * TimeSpan.TicksPerMillisecond);` (doesn't necessarily conserve the `DateTimeKind` of the `DateTime`). Another way would be `firstDateTime = firstDateTime.AddTicks(-(firstDateTime.Ticks % TimeSpan.TicksPerMillisecond));`. – Jeppe Stig Nielsen Jul 15 '13 at 19:02