有趣的问题:) 我写了这个小测试程序来尝试一下。如果您认为它有意义,您应该能够根据您的需要进行调整。基本上,从一个基本日期时间开始,在相同的 24 小时内生成一个随机的“测试”,然后随机生成一堆额外的时间,然后看看哪个与测试值的差异最小(在你的情况下会成为被比较的那个)。
List<DateTime> times = new List<DateTime>();
Random rnd = new Random();
int hourCount = (24 * 60) - 1;
DateTime dtBase = DateTime.Parse("01/01/2012 12:00 AM");
DateTime dtTest = dtBase.AddMinutes(rnd.Next(0, hourCount));
Console.WriteLine("Base: " + dtBase.ToString());
Console.WriteLine("Test: " + dtTest.ToString());
Console.WriteLine();
for (int i = 0; i < 24; i++) {
times.Add(dtBase.AddMinutes(rnd.Next(0, hourCount)));
}
times.Sort();
TimeSpan lastSpan = TimeSpan.MaxValue;
DateTime dtMatch = DateTime.Now;
foreach (DateTime dt in times) {
Console.Write(" " + dt.ToString());
var diff = (dtTest - dt).Duration();
if (diff < lastSpan) {
lastSpan = diff;
dtMatch = dt;
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("Closest match to {0:hh:mm tt} => {1:hh:mm tt} ({2})", dtTest, dtMatch, lastSpan);
示例输出运行:
Base: 1/1/2012 12:00:00 AM
Test: 1/1/2012 3:28:00 AM
1/1/2012 1:03:00 AM
1/1/2012 2:51:00 AM
1/1/2012 2:52:00 AM
1/1/2012 3:22:00 AM
1/1/2012 4:30:00 AM
1/1/2012 4:36:00 AM
1/1/2012 5:50:00 AM
1/1/2012 5:55:00 AM
1/1/2012 6:50:00 AM
1/1/2012 7:05:00 AM
1/1/2012 7:17:00 AM
1/1/2012 8:53:00 AM
1/1/2012 9:25:00 AM
1/1/2012 11:59:00 AM
1/1/2012 12:22:00 PM
1/1/2012 12:51:00 PM
1/1/2012 2:04:00 PM
1/1/2012 3:01:00 PM
1/1/2012 3:26:00 PM
1/1/2012 4:19:00 PM
1/1/2012 6:15:00 PM
1/1/2012 11:02:00 PM
1/1/2012 11:28:00 PM
1/1/2012 11:50:00 PM
Closest match to 03:28 AM => 03:22 AM (00:06:00)
因此,您的实际功能如下所示:
DateTime GetClosestTime(DateTime testTimeValue, List<DateTime> listItems) {
TimeSpan lastSpan = TimeSpan.MaxValue;
DateTime dtMatch = DateTime.Now;
foreach (DateTime dt in listItems) {
var diff = (testTimeValue - dt).Duration();
if (diff < lastSpan) {
lastSpan = diff;
dtMatch = dt;
}
}
return dtMatch;
}
假设您有时间与其他位置进行比较,您可以重写它以省略testTimeValue
参数。
希望这可以帮助!