If you want to, you can solve this problem with NSCalendar
without any looping. You could accomplish this by dividing up the problem
Basic idea
const NSUInteger Sunday = 1, ....., Saturday = 7;
NSUInteger workdaysCount
= getNumberOfDaysInMonth(today)
- getWeekdayCountInMonth(today, Saturday)
- getWeekdayCountInMonth(today, Sunday);
Now, we have two functions to implement:
Get the number of days in a month
You already got it right,
NSUInteger getNumberOfDaysInMonth(NSDate* date) {
NSCalendar *c = [NSCalendar currentCalendar];
return [c rangeOfUnit:NSCalendarUnitDay
inUnit:NSMonthCalendarUnit
forDate:date].length;
}
Get the count of a given weekday in a month
This is the trickier one, but NSCalendar
provides the basic building blocks:
NSUInteger getWeekdayCountInMonth(NSDate* date, enum Weekdays weekday) {
NSCalendar *c = [NSCalendar currentCalendar];
NSDate* startOfMonth = getMonthStart(date);
NSDate* firstMatchingWeekday = [c dateBySettingUnit:NSWeekdayCalendarUnit value:weekday ofDate:startOfMonth options:0];
// Number of days from start of month until we are at given weekday
NSUInteger daysToWeekday = [c components:NSDayCalendarUnit
fromDate:startOfMonth
toDate:firstMatchingWeekday options:0].day;
NSUInteger days = getNumberOfDaysInMonth(date) - daysToWeekday;
return (days + 6) / 7;
}