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;
}