如何获得2个范围之间的重叠天数? [英] How to gets the number of overlapping days between 2 ranges?
本文介绍了如何获得2个范围之间的重叠天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我先解释一下情况-假设我有4个约会:BS,BE,PS,PE(S代表开始,E代表结束)。
在给定这些日期的时候,我需要知道有多少天会重叠。例如
:BE-05.01,BS-10.01,PS-03.01,PE-07.01
结果是:3(05.01、06.01和07.01重叠)
let me explain the situation first - let's say i have 4 dates: BS, BE, PS, PE (S for start, E for end). I need to know how many days are over lapping when given those dates. for example : BE-05.01 , BS-10.01, PS-03.01, PE-07.01 the result is: 3 (05.01, 06.01 and 07.01 are overlapping)
我写了以下代码,但看起来很乱,我想检查一下是否有更简单的方法可以做到这一点:
I wrote the following code but it seems to messy and i want to check if maybe there is a simpler way to do this:
private static double GetNumOfOverLappingDays(DateTime BS, DateTime BE, DateTime PS, DateTime PE)
{
//case 1:
// |--- B ---|
// |----P ---|
//case 2:
// |--- B ---|
// | --- P --- |
//case 3:
// |--- B ---|
// | --- P ---- |
//case 4:
// |--- B ---|
// | - P - |
//case 5:
// |--- B ---|
// | -------- P -------- |
double days = -1;
bool isNotOverLap = (BS > PE) || (PS > BE);
if (isNotOverLap == false)
{
//case 1
if (BS == PS && BS == PE)
{
days = (PE - PS).TotalDays;
}
//case 2
else if (BE > PS && BE < PE)
{
days = (BE - PS).TotalDays;
}
//case 3
else if (BS > PS && BS < PE)
{
days = (PE - BS).TotalDays;
}
//case 4
else if (BS < PS && BE > PE)
{
days = (PE - PS).TotalDays;
}
//case 5
else if (BS > PS && BE < PE)
{
days = (BE - PS).TotalDays;
}
}
return days+1;
}
在此感谢您的协助,
提交
推荐答案
尝试以下操作:
private static double GetOverlappingDays(DateTime firstStart, DateTime firstEnd, DateTime secondStart, DateTime secondEnd)
{
DateTime maxStart = firstStart > secondStart ? firstStart : secondStart;
DateTime minEnd = firstEnd < secondEnd ? firstEnd : secondEnd;
TimeSpan interval = minEnd - maxStart;
double returnValue = interval > TimeSpan.FromSeconds(0) ? interval.TotalDays : 0;
return returnValue;
}
这篇关于如何获得2个范围之间的重叠天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文