Translate

Friday 14 September 2012

Age calculation from the given NSDate using categories

Hi friends i glad to share my ideas and my workouts here.....

Scenario :
      Need to calculate the age of the person....
 
 category file content will be of this.....
           .h file code will be :-

#import <Foundation/Foundation.h>

@interface NSDate (AdditionalMethods)

- (NSInteger)age;

@end

.m file code will be :-
#import "NSDate+AdditionalMethods.h"

@implementation NSDate (AdditionalMethods)


- (NSInteger)age {
   
    NSCalendar *calendar = [NSCalendar currentCalendar];
   
    unsigned flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
   
    NSDateComponents *dateComponentsNow = [calendar components:flags fromDate:[NSDate date]];
    NSDateComponents *dateComponentsBirth = [calendar components:flags fromDate:self];
   
    if (([dateComponentsNow month] < [dateComponentsBirth month]) || (([dateComponentsNow month] == [dateComponentsBirth month]) && ([dateComponentsNow day] < [dateComponentsBirth day]))) {
        return [dateComponentsNow year] - [dateComponentsBirth year] - 1;
    } else {
        return [dateComponentsNow year] - [dateComponentsBirth year];
    }
}


@end


The method call will be....

    NSString *dateStr = @"20081122";
   
    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMdd"];
    NSDate *date = [dateFormat dateFromString:dateStr]; 
   
    // Convert date object to desired output format
    [dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
    dateStr = [dateFormat stringFromDate:date]; 
    [dateFormat release];
    NSLog(@"Age now: %d",date.age);



you may download from here 

No comments:

Post a Comment