arnieterm
May 26, 2009, 06:01 AM
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
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 (http://www.easycalculation.com/date-day/age-calculator.php)
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
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 (http://www.easycalculation.com/date-day/age-calculator.php)
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
