Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

arnieterm

macrumors regular
Original poster
Aug 28, 2008
201
0
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.