Thursday, June 13, 2013

NSCalendar rangeOfUnit example in Objective C (iOS).


NSCalendar rangeOfUnit

Returns the range of absolute time values that a smaller calendar unit (such as a day) can take on in a larger calendar unit (such as a month) that includes a specified absolute time.

- (NSRange)rangeOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date

Parameters
smaller
The smaller calendar unit.
larger
The larger calendar unit.
date
The absolute time for which the calculation is performed.

Return Value of [NSCalendar rangeOfUnit]
The range of absolute time values smaller can take on in larger at the time specified by date. Returns {NSNotFound, NSNotFound} if larger is not logically bigger than smaller in the calendar, or the given combination of units does not make sense (or is a computation which is undefined).

Discussion of [NSCalendar rangeOfUnit]
You can use this method to calculate, for example, the range the Day unit can take on in the Month in which date lies.

NSCalendar rangeOfUnit example.
You can use the NSDate and NSCalendar classes:

NSDate *today = [NSDate date]; //Get a date object for today's date
NSCalendar *c = [NSCalendar currentCalendar];
NSRange days = [c rangeOfUnit:NSDayCalendarUnit
                       inUnit:NSMonthCalendarUnit
                      forDate:today];

Example of [NSCalendar rangeOfUnit].
- (NSDate*)boundaryForCalendarUnit:(NSCalendarUnit)calendarUnit
{
    NSDate *boundary;
    [[NSCalendar currentCalendar] rangeOfUnit:calendarUnit startDate:&boundary interval:NULL forDate:self];
    return boundary;
}

- (NSDate*)dayBoundary
{
    return [self boundaryForCalendarUnit:NSDayCalendarUnit];
}

NSCalendar rangeOfUnit example.
The following works on Mac or iPhone (no dateWithNaturalLanguageString: available there).

NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comps = [[[NSDateComponents alloc] init] autorelease];

// Set your month here
[comps setMonth:1];

NSRange range = [cal rangeOfUnit:NSDayCalendarUnit
                          inUnit:NSMonthCalendarUnit
                         forDate:[cal dateFromComponents:comps]];
NSLog(@"%d", range.length);

End of NSCalendar rangeOfUnit example article.