George Friday
George Friday

Reputation: 585

Overlap of a Date Range with Other Date Ranges

Good Evening,

I am trying to figure out how to count the number of days between date ranges by comparing the date ranges. For example, I have three given ranges:

range_1 01/01/2001 to 01/01/2002
range_2 01/02/2002 to 01/01/2003
range_3 01/02/2003 to 01/01/2004

If I compare my_date_range 12/12/2001 to 01/05/2002 with the ranges above, the result should show that between range_1 and my_date_range there are 19 days, between range_2 and my_date_range there are 5 days, and between range_3 and my_date_range there are 0 days.

In Excel this was easy, I would simply use:

=SUMPRODUCT(ISNUMBER(MATCH(ROW(INDIRECT(A1&":"&B1)),ROW(INDIRECT($C$1&":"&$D$1)),0))*1)

where A1 and B1 are the start and end dates the user enters, and C1 and D1 is one of the three date ranges. I would then use the same formula and compare A1 and B1 to the second date range, then the third.

But how is this translated into objective-c? (I am able to compare two dates and get the number of days between them.)

Upvotes: 3

Views: 1813

Answers (2)

Ben Packard
Ben Packard

Reputation: 26476

Once you have your start/end dates as per Martin's answer, you can use the intersection(with) function on DateInterval:

let interval1 = DateInterval(start: start1, end: end1)
let interval2 =  DateInterval(start: start2, end: end2)
let intersection = interval1.insection(with: interval2)

Also helpful if you just want to check for an overlap is interval1.intersects(interval2).

Upvotes: 1

Martin R
Martin R

Reputation: 539775

First you have to convert the date strings to NSDate values:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];

NSDate *range1Start = [dateFormatter dateFromString:@"01/01/2001"];
NSDate *range1End   = [dateFormatter dateFromString:@"01/01/2002"];

NSDate *userStart   = [dateFormatter dateFromString:@"12/12/2001"];
NSDate *userEnd     = [dateFormatter dateFromString:@"01/05/2002"];

Then you can compute the overlapping interval:

NSDate *overlapFrom = [range1Start laterDate:userStart];
NSDate *overlapTo   = [range1End earlierDate:userEnd];

And finally the number of days between the start and end date of the overlapping interval:

NSInteger days;
if ([overlapFrom compare:overlapTo] > 0) {
    // Date ranges do not overlap
    days = 0;
} else {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSDayCalendarUnit fromDate:overlapFrom toDate:overlapTo options:0];
    days = [comp day];
}
NSLog(@"%ld", (long)days);

In this example, the output is 20, because the difference between 12/12/2001 and 01/01/2002 is 20 days. You have to add 1 if both start and end day of the overlapping range should be counted.

Upvotes: 8

Related Questions