List<DateTime>
"2015-03-21 13:00:00"
"2015-05-15 13:00:00"
"2015-05-24 13:00:00"
"2015-05-27 13:00:00"
"2015-06-14 13:00:00"
我有开始日期(2015-05-21 13:00:00
)和结束日期(2015-06-09 22:00:00
)
实际上我需要从上面的数组中得到两个日期,它们更接近或等于开始日期和结束日期。
另外请注意,最接近开始日期的日期应等于或早于开始日期,并且最接近结束日期的日期应等于或等于结束日期。换句话说,给定日期列表,找到包含开始日期和结束日期的最小日期范围。
在这种情况下,输出将为“2015-05-15 13:00:00
”和“2015-06-14 13:00:00
”。
如何在c#中实现这一目标?
答案 0 :(得分:3)
void Main()
{
var dates = new string[]
{
"2015-03-21 13:00:00",
"2015-05-15 13:00:00",
"2015-05-24 13:00:00",
"2015-05-27 13:00:00",
"2015-06-14 13:00:00"
}
.Select(x => DateTime.Parse(x))
.ToList();
var start = DateTime.Parse("2015-05-21 13:00:00");
var end = DateTime.Parse("2015-06-09 22:00:00");
Console.WriteLine(dates
.Where(x => x <= start)
.OrderByDescending(x => x)
.FirstOrDefault());
Console.WriteLine(dates
.Where(x => x >= end)
.OrderBy(x => x)
.FirstOrDefault());
}
// the date must be outside of boundary, so this is no longer good...
//public static DateTime GetClosestDate(IEnumerable<DateTime> source, DateTime date)
//{
// return source
// .OrderBy(x => Math.Abs((x.Date - date).TotalSeconds))
// .First();
//}
结果:
GetClosestDate:
2015-05-24 13:00:00
2015-06-14 13:00:00OrderBy [Descending] FirstOrDefault:
2015-05-15 13:00:00
2015-06-14 13:00:00
答案 1 :(得分:2)
public DateTime? GetClosest(List<DateTime> dates, DateTime dateToCompare)
{
DateTime? closestDate = null;
int min = int.MaxValue;
foreach (DateTime date in dates)
{
if (Math.Abs(date.Ticks - dateToCompare.Ticks) < min)
{
min = date.Ticks - dateToCompare.Ticks;
closestDate = date;
}
}
return closestDate;
}
Google上的简单搜索与this
相关