Thursday, June 13, 2013

NSCalendar rangeOfUnit inUnit forDate example in Objective C (iOS).


NSCalendar rangeOfUnit inUnit forDate

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 of [NSCalendar rangeOfUnit inUnit forDate]
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 inUnit forDate]
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 inUnit forDate]
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 inUnit forDate 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 inUnit forDate].
NSUInteger days = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:today];
NSUInteger months = [calendar rangeOfUnit:NSMonthCalendarUnit
                                   inUnit:NSYearCalendarUnit
                                  forDate:today].length;
for (int i = 1; i <= months; i++) {
    components.month = i;
    NSDate *month = [calendar dateFromComponents:components];
    days += [calendar rangeOfUnit:NSDayCalendarUnit
                           inUnit:NSMonthCalendarUnit
                          forDate:month].length;
}

return days;

NSCalendar rangeOfUnit inUnit forDate 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 inUnit forDate example article.