Thursday, June 13, 2013

NSCalendar maximumRangeOfUnit example in Objective C (iOS).

NSCalendar maximumRangeOfUnit

The maximum range limits of the values that a given unit can take on in the receive

- (NSRange)maximumRangeOfUnit:(NSCalendarUnit)unit

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

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

Discussion of [NSCalendar maximumRangeOfUnit]
As an example, in the Gregorian calendar the maximum range of values for the Day unit is 1-31.

NSCalendar maximumRangeOfUnit example.
NSDate *aDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSRange weekdayRange = [calendar maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:aDate];
NSUInteger weekdayOfDate = [components weekday];

if (weekdayOfDate == weekdayRange.location || weekdayOfDate == weekdayRange.length) {
  //the date falls somewhere on the first or last days of the week

Example of [NSCalendar maximumRangeOfUnit].
NSInteger desiredWeekday = 3; // Tuesday

NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1;;

NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]];

NSInteger currentWeekday = dateComponents.weekday;
NSInteger differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek;

NSDateComponents *daysComponents = [[NSDateComponents alloc] init]; = differenceDays;

NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:[NSDate date] options:0];

NSLog(@"newDate: %@", newDate);

NSCalendar maximumRangeOfUnit example.
NSDate *referenceDate = [NSDate date];
NSDate *startOfThisWeek;
NSDate *saturday;

NSUInteger backupStartWeekday = [[NSCalendar currentCalendar] firstWeekday];
[[NSCalendar currentCalendar] setFirstWeekday:1]; // ensure week begins at sunday

[[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit

NSDateComponents *components = [[NSDateComponents alloc] init]; = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSWeekdayCalendarUnit].length; //the start of the next week = - 2;
saturday = [[NSCalendar currentCalendar] dateByAddingComponents:components

[[NSCalendar currentCalendar] setFirstWeekday:backupStartWeekday];

End of NSCalendar maximumRangeOfUnit example article.