Sometimes getting wrong age

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

  1. arnieterm macrumors regular

    Joined:
    Aug 28, 2008
    #1
    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


    Code:
    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
    												fromDate:startDate
    												  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
    AGE
    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?
    Thanks
    Arnieterm
     
  2. dejo Moderator

    dejo

    Staff Member

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

Share This Page