Sometimes getting wrong age

Discussion in 'iOS Programming' started by arnieterm, May 26, 2009.

  1. arnieterm macrumors regular

    Aug 28, 2008
    I have created a function as given below that calculates the age in years, month and days based on supplied date of birth. I have noticed that for some dates I do not get the correct results. Not able to point out why this is happening

    NSDate *startDate = [NSDate dateWithNaturalLanguageString:dateofbirth locale:[NSLocale currentLocale] ];
    	NSDate *endDate =  [NSDate date] ;
    	NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    	NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    	NSDateComponents *components = [gregorian components:unitFlags
    												  toDate:endDate options:0];
    	NSInteger years = [components year];
    	NSInteger months = [components month];
    	NSInteger days = [components day];	
    	NSString* yearsPassed = [NSString stringWithFormat:@"%dy", years];
    	NSString* monthsPassed = [NSString stringWithFormat:@"%dm", months];
    	NSString* daysPassed = [NSString stringWithFormat:@"%dd", days];
    The below given link will be helpful in cross checking the age calculated by the above function
    A sample date: 14th January, 1959. The above code returns
    49years, 11 months and 18 days
    But the calculated age from the link [which is correct] is
    50years, 4 months and 12 days
    I have also tried replacing 0 with NSWrapCalendarComponents in the options but still the same discrepancy
    Can anybody point out the reason for this?
  2. dejo Moderator


    Staff Member

    Sep 2, 2004
    The Centennial State
    Perhaps the current locale is handling month/day or day/month different than you are expecting?

Share This Page