Timespan intersection in c#

前端 未结 2 585
别跟我提以往
别跟我提以往 2020-12-20 17: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. <

相关标签:
2条回答
  • 2020-12-20 17:36

    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.

    0 讨论(0)
  • 2020-12-20 17:45

    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.

    0 讨论(0)
提交回复
热议问题