鉴于日期列表(可能没有排序),我想建立一个日期范围列表 -
E.g。假设MM / DD格式,
输入 - 5/1, 5/5, 5/6, 5/15, 5/7, 5/8, 5/19,5/20, 5/23
输出 -
Date Range 1: 5/1 to 5/1 Date Range 2: 5/5 to 5/8 Date Range 3: 5/15 to 5/15 Date Range 4: 5/19 to 5/20 Date Range 5: 5/23 to 5/23
基本上,范围应该是连续的。
答案 0 :(得分:5)
答案 1 :(得分:0)
您可以创建DateTime
的列表(可能对所有人使用相同年份)并对其进行排序。
然后很容易找到列表中是否存在一天和第二天(使用DateTime.AddDays(1)
)。
答案 2 :(得分:0)
public class DateRange
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
[TestClass]
public class DateRangerTest
{
private List<DateRange> GetDateRanges(List<DateTime> dates)
{
if (dates == null || !dates.Any()) return null;
dates = dates.OrderBy(x => x.Date).ToList();
var dateRangeList = new List<DateRange>();
DateRange dateRange = null;
for (var i = 0; i < dates.Count; i++)
{
if (dateRange == null)
{
dateRange = new DateRange { Start = dates[i] };
}
if (i == dates.Count - 1 || dates[i].Date.AddDays(1) != dates[i + 1].Date)
{
dateRange.End = dates[i].Date;
dateRangeList.Add(dateRange);
dateRange = null;
}
}
return dateRangeList;
}
[TestMethod]
public void GetDateRanges_MultiDateRangeTest()
{
var dates = new List<DateTime>
{
new DateTime(1999,5,1),
new DateTime(1999,5,5),
new DateTime(1999,5,6),
new DateTime(1999,5,15),
new DateTime(1999,5,7),
new DateTime(1999,5,8),
new DateTime(1999,5,19),
new DateTime(1999,5,20),
new DateTime(1999,5,23)
};
var dateRanges = GetDateRanges(dates);
Assert.AreEqual(new DateTime(1999, 5, 1), dateRanges[0].Start);
Assert.AreEqual(new DateTime(1999, 5, 1), dateRanges[0].End);
Assert.AreEqual(new DateTime(1999, 5, 5), dateRanges[1].Start);
Assert.AreEqual(new DateTime(1999, 5, 8), dateRanges[1].End);
Assert.AreEqual(new DateTime(1999, 5, 15), dateRanges[2].Start);
Assert.AreEqual(new DateTime(1999, 5, 15), dateRanges[2].End);
Assert.AreEqual(new DateTime(1999, 5, 19), dateRanges[3].Start);
Assert.AreEqual(new DateTime(1999, 5, 20), dateRanges[3].End);
Assert.AreEqual(new DateTime(1999, 5, 23), dateRanges[4].Start);
Assert.AreEqual(new DateTime(1999, 5, 23), dateRanges[4].End);
}
}