C# Closest Date

DateTime type illustration

Your C# program contains a List of many DateTimes and you want to determine which two dates are the closest together. An algorithm that sorts first on the DateTimes and then on the difference between the DateTimes can determine this for you.

Closest date algorithm

To begin, this program creates a List of four 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 uses a for-loop to compare each DateTime to the following DateTime. It adds Tuple instances to a List containing the TimeSpan delta and both DateTimes.

Program that finds closest dates [C#]

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)

Sort by TimeSpan. 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. Finally, the very first Tuple in the sorted list has the lowest TimeSpan, so that pair of DateTime instances is the nearest in time to each other.

Comparison Delegate TimeSpan Examples Tuple Tips

Uses

Programming tip

Finding the nearest of two DateTimes could have many different applications. It would 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. For small collections, other methods would likely be faster.

Time Representations
.NET