you need to use NSDateComponents. Like this:
NSDate *date = [NSDate date]; NSUInteger componentFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSDateComponents *components = [[NSCalendar currentCalendar] components:componentFlags fromDate:date]; NSInteger year = [components year]; NSInteger month = [components month]; NSInteger day = [components day];
Is there any direct way to compare years?
not built in. But you can write a category for it. Like this:
@interface NSDate (YearCompare) - (BOOL)yearIsEqualToDate:(NSDate *)compareDate; @end @implementation NSDate (YearCompare) - (BOOL)yearIsEqualToDate:(NSDate *)compareDate { NSDateComponents *myComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:self]; NSDateComponents *otherComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:compareDate]; if ([myComponents year] == [otherComponents year]) { return YES; } return NO; } @end
source share