I am developing a scheduling application, and part of it are events that repeat, say, daily in a given schedule. This schedule is only 'active' on certain days—think of it like a work week, where Saturdays and Sundays nothing happens.
I'd like to calculate the number of consecutive days between two dates, excluding those certain weekdays. I have a method that uses NSCalendar
to do this, ignoring the excluded days, but did not see any methods on it (or related classes) that'd allow me to ignore certain days.
+ (NSInteger) OKDaysBetweenDate:(nonnull NSDate *) fromDateTime
andDate:(nonnull 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];
}
A possibility I have thought of is checking how many weeks are between the two dates, multiplying that by the number of excluded days a week, and subtracting it from the end result, but that doesn't seem particularly clean to me.
Is there a better, more Cocoa-y (perhaps using NSCalendar
or friends) way of implementing this?
Thanks.