Getting number of days where a range of NSDates intersects another range of NSDates

StackOverflow https://stackoverflow.com/questions/23545712

  •  18-07-2023
  •  | 
  •  

Question

I have a problem on getting the number of days where a range of NSDates intersects another range of NSDates.

Scenario1:
Main Range: March8 - June8
Range to check: April8 - May8
Then the number of days that intersects is the number of days from April8 - May8

Scenario2:
Main Range: March8 - June8
Range to check: Feb8 - March15
Then the number of days that intersects is the number of days from March8 - March15

Scenario3:
Main Range: March8 - June8
Range to check: May19 - June15
Then the number of days that intersects is the number of days from May19 - June8

Scenario4:
Main Range: March8 - June8
Range to check: March1 - June9
Then the number of days that intersects is the number of days from March8 - June8

I tried to use below code by first using startdate1(Range to check) and startdate2(Main Range). If positive I'll include, otherwise I won't. Then use enddate1(Range to check) and enddate2(Main Range). If positive I'll include, otherwise I won't. Then sum up all positive values. This solution I read from one of the post but it doesn't look correct.

+ (NSInteger)daysBetweenTwoDates:(NSDate *)fromDateTime andDate:(NSDate*)toDateTime
{
    NSDate *fromDate;
    NSDate *toDate;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:fromDateTime];
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:toDateTime];
    NSDateComponents *difference = [calendar components:NSDayCalendarUnit fromDate:fromDate toDate:toDate options:0];
    return [difference day] + 1;
}
Was it helpful?

Solution

Your method only takes two dates, so you need to get the proper two dates to supply to that method.

Assuming they intersect at all:

To do that all you need to do is take the two start dates and compare them, then take the two end dates and compare them. The last start date and the earliest end date will govern your range of intersection.

NSDate* correctStartDate;
NSComparisonResult result = [startdate1 compare:startdate2];
if(result == NSOrderedDescending)
    correctStartDate = startdate1;
else
    correctStartDate = startdate2;

NSDate* correctEndDate;
NSComparisonResult result = [enddate1 compare:enddate2];
if(result == NSOrderedAscending)
    correctEndDate = enddate1;
else
    correctEndDate = enddate2;

Then get the number of days between those using your method.

To check if they intersect just compare the start date and the end date. If the start is after the end then they do not intersect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top