Timespan intersection in c#

旧街凉风 提交于 2019-11-28 07:30:32

问题


Let's say i have 2 date ranges.

Those date ranges could be represented as time spans.

i want to find a date range, that falls within the 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)

so in this case, the intersection would be 5/2/2011-5/28/2011, but the ranges could move in either direction, (or not intersect at all in which case i'd want the resulting timespan to be 0 length)

in the end, i need the calendar dates of start/end of the resulting intersection time span (not just ticks/hours/days etc)

is there a elegant way to do this in c# 3.0?

UPDATE

i took StriplingWarriors code and created a method out of 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;
    }

回答1:


Something like this, perhaps?

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 intersecting time period.




回答2:


Simple way is to deduct Start time of range 1 with start time of range 2. If time span > 0 then select range 1 start as start date.

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

Then compare results if both are valid range. Ie start < end. Otherwise there is no valid range.



来源:https://stackoverflow.com/questions/6837675/timespan-intersection-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!