C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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)
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.
ComparisonTimeSpanTuple