Intersection of a time interval in C #

Say I have 2 date ranges.

These date ranges can be represented as time intervals.

I want to find a date range that falls in two time spans.

Range 1: 2/1/2011 - 8/1/2011 (timespan of 6 months) Range 2: 5/2/2011 - 5/28/2011 (timespan of 26 days) 

therefore, in this case, the intersection will be 5/2 / 2011-5 / 28/2011, but the ranges can move in any direction (or not intersect at all, in which case I want the resulting time period to be length 0)

after all, I need calendar dates for the start / end of the resulting intersection interval (not just ticks / hours / days, etc.)

Is there an elegant way to do this in C # 3.0?

UPDATE

I took the StriplingWarriors code and created a method from it.

  private static DateRange GetIntersectionRange(DateRange range1, DateRange range2) { var iRange = new DateRange(); iRange.From = range1.From < range2.From ? range2.From : range1.From; iRange.To = range1.To < range2.To ? range1.To : range2.To; if (iRange.From > iRange.To) iRange = null; return iRange; } 
+6
source share
2 answers

Something like this, maybe?

 var range1 = new{start = DateTime.Parse("2/1/2011"), end = DateTime.Parse("8/1/2011")}; var range2 = new{start = DateTime.Parse("5/2/2011"), end = DateTime.Parse("5/28/2011")}; var iStart = range1.start < range2.start ? range2.start : range1.start; var iEnd = range1.end < range2.end ? range1.end : range2.end; var newRange = iStart < iEnd ? new{start = iStart, end = iEnd} : null; 

This should return null if there is no overlapping time period.

+10
source

A simple way is to subtract the start time of range 1 with the start time of range 2. If the time interval is> 0, then select range 1 starting from the start date.

Do the same for the end date of the range. But if the time interval is> 0, select the end date of range 2.

Then compare the results if both ranges are valid. Those. beginning <end. Otherwise, the valid range will not be.

0
source

Source: https://habr.com/ru/post/893649/


All Articles