Count of days intersecting between two date ranges
Would anyone have any ideas of how to best calculate开发者_C百科 the amount of days that intersect between two date ranges?
Here's a little method I wrote to calculate this.
private static int inclusiveDays(DateTime s1, DateTime e1, DateTime s2, DateTime e2)
{
// If they don't intersect return 0.
if (!(s1 <= e2 && e1 >= s2))
{
return 0;
}
// Take the highest start date and the lowest end date.
DateTime start = s1 > s2 ? s1 : s2;
DateTime end = e1 > e2 ? e2 : e1;
// Add one to the time range since its inclusive.
return (int)(end - start).TotalDays + 1;
}
Obtain a new range, defined by the later of the beginnings and the earlier of the ends, and determine the number of days since the beginning of the epoch for each day in that new range.
The difference is the number of days in the intersection. Accept only positive values.
Edited to take into account ranges instead of individual dates.
Here is an example from R. That might clarify the answer.
c_st = as.POSIXct("1996-10-14")
c_ed = as.POSIXct("1996-10-19")
d_st = as.POSIXct("1996-10-17")
d_ed = as.POSIXct("1999-10-22")
max(range(c_st,c_ed ))-min(range(d_st,d_ed) ) >= 0 & min(range(c_st,c_ed )) < max(range(d_st,d_ed) )
True would indicate that they intersect, False otherwise. [r]
If I understand your question, you're asking for the number of days that overlap two date ranges, such as: Range 1 = 2010-1-1 to 2010-2-1 Range 2 = 2010-1-5 to 2010-2-5 in this example the number of intersecting days would be 28 days.
Here is a code sample for that example
DateTime rs1 = new DateTime(2010, 1, 1);
DateTime re1 = new DateTime(2010, 2, 1);
DateTime rs2 = new DateTime(2010, 1, 5);
DateTime re2 = new DateTime(2010, 2, 5);
TimeSpan d = new TimeSpan(Math.Max(Math.Min(re1.Ticks, re2.Ticks) - Math.Max(rs1.Ticks, rs2.Ticks) + TimeSpan.TicksPerDay, 0));
The question asks between two date Ranges not two Dates. (Edited in response to comments)
So if you have 2 Date Ranges (r1s,r1e), you need to determine which starts first, Is there overlap, and what is the overlap.
double overlap(DateTime r1s, DateTime r1e, DateTime r2s, DateTime r1e){
DateTime t1s,t1e,t2s,t2e;
if (rs1<rs2) //Determine which range starts first
{
t1s = r1s;
t1e = r1e;
t2s = r2s;
t2e = r2e;
}
else
}
t1s = r2s;
t1e = r2e;
t2s = r1s;
t2e = r1e;
}
if (t1e<t2s) //No Overlap
{
return -1;
}
if (t1e<t2e) //Partial Overlap
}
TimeSpan diff = new TimeSpan(t1e.Ticks - t2s.Ticks);
{
else //Range 2 totally withing Range 1
}
TimeSpan diff = new TimeSpan(t2e.Ticks - t2s.Ticks);
{
double daysDiff = diff.TotalDays;
return daysDiff;
}
精彩评论