Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

.net - Timespan intersection in c#

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;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...