Thursday, June 13, 2013

NSCalendar rangeOfUnit startDate interval forDate example in Objective C (iOS).


NSCalendar rangeOfUnit startDate interval forDate

Returns by reference the starting time and duration of a given calendar unit that contains a given date.

- (BOOL)rangeOfUnit:(NSCalendarUnit)unit startDate:(NSDate **)datep interval:(NSTimeInterval *)tip forDate:(NSDate *)date

Parameters
unit
A calendar unit (see “Calendar Units” for possible values).
datep
Upon return, contains the starting time of the calendar unit unit that contains the date date
tip
Upon return, contains the duration of the calendar unit unit that contains the date date
date
A date.

Return Value of [NSCalendar rangeOfUnit startDate interval forDate]
YES if the starting time and duration of a unit could be calculated, otherwise NO.

NSCalendar rangeOfUnit startDate interval forDate example.
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date1 interval:NULL forDate:date1];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date2 interval:NULL forDate:date2];

NSComparisonResult result = [date1 compare:date2];
if (result == NSOrderedAscending) {
} else if (result == NSOrderedDescending) {
}  else {
    //the same
}

Example of [NSCalendar rangeOfUnit startDate interval forDate].
- (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 startDate interval forDate example.
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *startOfYear;
NSTimeInterval lengthOfYear;
[calendar rangeOfUnit:NSYearCalendarUnit
            startDate:&startOfYear
             interval:&lengthOfYear
              forDate:[NSDate date]];
NSDate *endOfYear = [startOfYear dateByAddingTimeInterval:lengthOfYear];
NSDateComponents *comp = [calendar components:NSDayCalendarUnit
                                     fromDate:startOfYear
                                       toDate:endOfYear
                                      options:0];
NSUInteger numberOfDaysInThisYear = [comp day];

End of NSCalendar rangeOfUnit startDate interval forDate example article.