I'm using the following code to convert a user-supplied birthdate to its equivalent years from the current date. The output is always off by an inconsistent amount in years and very large numbers in days and months.
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc] init];
[tempFormatter setDateFormat:@"yyyy-mm-dd hh:mm:ss"];
NSDate *birthDate = [tempFormatter dateFromString:[NSString stringWithFormat:@"%@-%@-%@ 01:00:00",self.birthYear.text,self.birthMonth.text,self.birthDay.text]];
NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:birthDate
toDate:now
options:0];
NSInteger years = [ageComponents year];
NSInteger days = [ageComponents day];
NSInteger months = [ageComponents month];
NSLog(@"Years: %ld, Days: %ld, Months: %ld",years,days, months);
What gets outputted when I input "06-16-1986"
is the following
Years: 28, Days: 9223372036854775807, Months: 9223372036854775807
The year is off by 1 and the months and days are producing extremely large numbers. I get the same issue using various dates. For example, "12-07-1989"
produces
Years: 25, Days: 9223372036854775807, Months: 9223372036854775807
What am I doing wrong here?
Add
|NSMonthCalendarUnit|NSDayCalendarUnit
to your components, change the date format fromyyyy-mm-dd hh:mm:ss
toyyyy-MM-dd hh:mm:ss
:the problem is in this line
if you want month & days to be calculated you need to include that in the components like this
also your format is wrong for month string
should be corrected as
now you will get correct date.
explanation. as mentioned on apple documentation these are 1-based. so incase you dont provide a value it will put 1 as default. so earlier your month format was "mm" and it was not correctly setting a month for the birthday hence it was 1986-01-16 so now its 2014-04-01 (in singapore). So you get 28 years which is correct.