Reputation: 2530
I have 2 NSDates that define a span, one could set them like this
spanA: 12:00 today
spanB: 12:00 tomorrow
This equals to 24 hours, but I need to create two ranges instead of one, so that no spans will stretch across midnight. The outcome of the example above would look like this:
spanA: 12:00 today
spanB: 23:59 today
spanC: 00:01 tomorrow
spanD: 12:00 tomorrow
I'm not sure how to do this. I came up with an idea to use a function like this:
- (NSInteger)daysBetweenDate:(NSDate *)fromDateTime andDate:(NSDate *)toDateTime
{
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate
interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&toDate
interval:NULL forDate:toDateTime];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay
fromDate:fromDate toDate:toDate options:0];
return [difference day];
}
which returns how many days the span stretches across, or in other words: the number of spans required. Then I could for instance for-loop the number of days and add some logic to create the necessary spans.
I'm using this as a structure for the spans:
typedef struct
{
NSTimeInterval start;
NSTimeInterval end;
} span;
What would be the best approach for this?
Upvotes: 2
Views: 107
Reputation: 727137
Since all spans except possibly the first and last one are identical day-long spans, you can use this algorithm:
Upvotes: 2