Comparing two dates or datetimes within an time interval in .NET

By Miguel Santos

This code will help you compare two dates or datetimes for a given interval. The sample code is shown in C# and VB.NET

This code will help you compare two dates or datetimes for an interval:

a) Within a second (exclude milliseconds)

           DateTime dt1 = new DateTime(2009, 12, 05, 12, 20, 30, 120);
           DateTime dt2 = new DateTime(2009, 12, 05, 12, 20, 30);
             if ((dt1-dt2).Duration() < TimeSpan.FromSeconds(1))
               Debug.WriteLine("Time differs less than a second");

b) Within a minute (exclude seconds and milliseconds)

           DateTime dt1 = new DateTime(2009, 12, 05, 12, 20, 30, 120);
           DateTime dt2 = new DateTime(2009, 12, 05, 12, 20, 30);
             if ((dt1 - dt2).Duration() < TimeSpan.FromMinutes(1))
               Debug.WriteLine("Time differs less than a minute");

The VB.NET equivalent of the code above:

a) Within a second (exclude milliseconds)

         Dim dt1 As DateTime = DateTime.Now
        Dim dt2 As DateTime = DateTime.Now.AddMilliseconds(800)
        If ((dt1 - dt2).Duration() < TimeSpan.FromSeconds(1)) Then
           Debug.WriteLine("Time differs less than a second")
        End If

b) Within a minute (exclude seconds and milliseconds)

        Dim dt1 As DateTime = DateTime.Now
        Dim dt2 As DateTime = DateTime.Now.AddMilliseconds(800)
        If ((dt1 - dt2).Duration() < TimeSpan.FromMinutes(1)) Then
           Debug.WriteLine("Time differs less than a minute")
        End If

TimeSpan has other methods that can help you to compare two date times by hours (FromHours) or days (FromDays).

Note: Any other solution will introduce round-off errors (e.g AddMilliseconds to get rid of milliseconds). The DateTime methods Compare and CompareTo only states whether the date time instances are equal or not but it does not provide a check for interval.

Comparing two dates or datetimes within an time interval in .NET  (4188 Views)