Thursday, June 13, 2013

NSCalendar minimumRangeOfUnit example in Objective C (iOS).

NSCalendar minimumRangeOfUnit

Returns the minimum range limits of the values that a given unit can take on in the receiver.

- (NSRange)minimumRangeOfUnit:(NSCalendarUnit)unit

Parameters of [NSCalendar minimumRangeOfUnit]
The unit for which the maximum range is returned.

Return Value
The minimum range limits of the values that the unit specified by unit can take on in the receiver.

Discussion of [NSCalendar minimumRangeOfUnit]
As an example, in the Gregorian calendar the minimum range of values for the Day unit is 1-28.

NSCalendar minimumRangeOfUnit example.
you'll need to know how many months the calendar has:

NSRange minMonthRange = [coptic minimumRangeOfUnit:NSMonthCalendarUnit]; // {1,13}
NSRange maxMonthRange = [coptic maximumRangeOfUnit:NSMonthCalendarUnit]; // {1,13}
So it looks like every year has 13 months. OK, how about days in a month?

NSRange minDayRange = [coptic minimumRangeOfUnit:NSDayCalendarUnit]; // {1,5}
NSRange maxDayRange = [coptic maximumRangeOfUnit:NSDayCalendarUnit]; // {1,30}

Example of [NSCalendar minimumRangeOfUnit].
Next, we count how many days from fromDate to the next desired weekday:

    NSInteger daysUntilDesiredWeekday = weekday - components.weekday;
    // If fromDate is a Wednesday and weekday is Monday (for example),
    // daysUntilDesiredWeekday is negative.  Fix that.
    NSRange weekdayRange = [self minimumRangeOfUnit:NSWeekdayCalendarUnit];
    if (daysUntilDesiredWeekday < weekdayRange.location) {
        daysUntilDesiredWeekday += weekdayRange.length;

End of NSCalendar minimumRangeOfUnit example article.