NSCalendar rangeOfUnit startDate interval forDate
- (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
}
[[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];
}
{
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];
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];