C# Closest Date (Find Dates Nearest in Time)

Compute the closest DateTimes in a List using Subtract and TimeSpan.
Closest date. A program contains a List of many DateTimes. We determine which 2 dates are the closest together. An algorithm that sorts first on the DateTimes, and then on the difference between the DateTimes, determines this.DateTime
To begin, this program creates a List of 4 DateTime instances. Next, it prints the result of the Closest() method. The Closest method first sorts the DateTime list in an ascending way (low to high).

Next: It compares each DateTime to the following one. It adds Tuple instances to a List containing the TimeSpan delta and both DateTimes.

C# program that finds closest dates using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { var list = new List<DateTime>(); list.Add(new DateTime(1980, 5, 5)); list.Add(new DateTime(1982, 10, 20)); list.Add(new DateTime(1984, 1, 4)); list.Add(new DateTime(1979, 6, 19)); Console.WriteLine(Closest(list)); // Add a very close date. list.Add(new DateTime(1980, 5, 6)); Console.WriteLine(Closest(list)); } /// <summary> /// Find closest two dates. /// </summary> static Tuple<TimeSpan, DateTime, DateTime> Closest(List<DateTime> list) { // Sort. list.Sort(); // Add tuples. var differences = new List<Tuple<TimeSpan, DateTime, DateTime>>(); for (int i = 0; i < list.Count - 1; i++) // Skip last. { // Compute difference. TimeSpan span = list[i + 1].Subtract(list[i]); // Add to tuple list. differences.Add(new Tuple<TimeSpan, DateTime, DateTime>(span, list[i], list[i + 1])); } // Sort on TimeSpan. differences.Sort((a, b) => a.Item1.CompareTo(b.Item1)); // Return closest. return differences.First(); } } Output (321.00:00:00, 6/19/1979 12:00:00 AM, 5/5/1980 12:00:00 AM) (1.00:00:00, 5/5/1980 12:00:00 AM, 5/6/1980 12:00:00 AM)
Finally, we use the List.Sort method with a custom Comparison to sort the Tuple list based on the Item1 property, which is the TimeSpan. We sort the TimeSpans in an ascending way, from low to high.

Result: The first Tuple in the sorted list has the lowest TimeSpan—that pair of DateTime instances is the nearest in time to each other.

Uses. This algorithm could be of use in scheduling tasks, or for finding errors in a schedule that exists. If you have a requirement that no two DateTimes can be too close, this algorithm would help you determine if an error exists.
Summary. This algorithm is one way you can determine the closest pair of DateTime instances in a List. Other options include recursion or nested loops. The performance of this method is not ideal and could be easily improved.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to