Return 日期列表中的相交日期范围
Return Intersected Date Range from a List of Dates
我有一个 Calendar 对象列表,其中包含 ParentId、StartDate 和 EndDate,它们代表工作班次中的休息时间。一个区域随时可能有许多班次,每个班次都有不同的休息时间。
我需要能够获取它们相交的日期范围,以便我可以确定何时每个区域目前都没有人在工作。
例如,如果我有以下换班休息时间:
new Calendar { ParentId = 1, StartDate = 2017-06-18 11:50:00, EndDate = 2017-06-18 12:20:00 };
new Calendar { ParentId = 2, StartDate = 2017-06-18 12:10:00, EndDate = 2017-06-18 12:40:00 };
new Calendar { ParentId = 3, StartDate = 2017-06-18 12:15:00, EndDate = 2017-06-18 12:45:00 };
那么我需要 return 的交叉时间是 12:15:00 - 12:20:00 因为那是该区域唯一没有人在场的时间。
我试过 Time Period For .NET 库,但它只告诉我存在交叉点,而不是交叉点的范围。
明确一点,我不想知道是否存在交叉或重叠,我需要知道它们发生的范围。
这对我有用:
var cals = new []
{
new { ParentId = 1, StartDate = DateTime.Parse("2017-06-18 11:50:00"), EndDate = DateTime.Parse("2017-06-18 12:20:00") },
new { ParentId = 2, StartDate = DateTime.Parse("2017-06-18 12:10:00"), EndDate = DateTime.Parse("2017-06-18 12:40:00") },
new { ParentId = 3, StartDate = DateTime.Parse("2017-06-18 12:15:00"), EndDate = DateTime.Parse("2017-06-18 12:45:00") },
};
var intersection =
cals
.Aggregate((c0, c1) => new
{
ParentId = -1,
StartDate = c0.StartDate > c1.StartDate ? c0.StartDate : c1.StartDate,
EndDate = c0.EndDate < c1.EndDate ? c0.EndDate : c1.EndDate
});
它给了我:
我有一个 Calendar 对象列表,其中包含 ParentId、StartDate 和 EndDate,它们代表工作班次中的休息时间。一个区域随时可能有许多班次,每个班次都有不同的休息时间。
我需要能够获取它们相交的日期范围,以便我可以确定何时每个区域目前都没有人在工作。
例如,如果我有以下换班休息时间:
new Calendar { ParentId = 1, StartDate = 2017-06-18 11:50:00, EndDate = 2017-06-18 12:20:00 };
new Calendar { ParentId = 2, StartDate = 2017-06-18 12:10:00, EndDate = 2017-06-18 12:40:00 };
new Calendar { ParentId = 3, StartDate = 2017-06-18 12:15:00, EndDate = 2017-06-18 12:45:00 };
那么我需要 return 的交叉时间是 12:15:00 - 12:20:00 因为那是该区域唯一没有人在场的时间。
我试过 Time Period For .NET 库,但它只告诉我存在交叉点,而不是交叉点的范围。
明确一点,我不想知道是否存在交叉或重叠,我需要知道它们发生的范围。
这对我有用:
var cals = new []
{
new { ParentId = 1, StartDate = DateTime.Parse("2017-06-18 11:50:00"), EndDate = DateTime.Parse("2017-06-18 12:20:00") },
new { ParentId = 2, StartDate = DateTime.Parse("2017-06-18 12:10:00"), EndDate = DateTime.Parse("2017-06-18 12:40:00") },
new { ParentId = 3, StartDate = DateTime.Parse("2017-06-18 12:15:00"), EndDate = DateTime.Parse("2017-06-18 12:45:00") },
};
var intersection =
cals
.Aggregate((c0, c1) => new
{
ParentId = -1,
StartDate = c0.StartDate > c1.StartDate ? c0.StartDate : c1.StartDate,
EndDate = c0.EndDate < c1.EndDate ? c0.EndDate : c1.EndDate
});
它给了我: