Florence Florence - 6 months ago 48
Objective-C Question

How to give age validation in ios?

Have created below function for age validation, but its not giving me proper out. Anyone know how to do it ?

Some other code tried but it was depricated. My app target is iOS 7 and later.


Selected Date - 13/03/1990 Output

You live since -68 years and -35 days


-(BOOL)validateAge

{

NSString *birthDate = _txtBirthDate.text;

NSDate *todayDate = [NSDate date];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd"];

int time = [todayDate timeIntervalSinceDate:[dateFormatter dateFromString:birthDate]];

int allDays = (((time/60)/60)/24);

int days = allDays%365;

int years = (allDays-days)/365;

NSLog(@"You live since %i years and %i days",years,days);

if(years>=18)

{

return YES;

}

else

{

return NO;

}

}

Answer

Your code looks perfect to me!

Problem seems to me is with your _txtBirthDate.text format. It should be in yyyy-MM-dd

I run your code with static string value in place of _txtBirthDate.text and got perfect result. Check below code for your reference.

    NSString *birthDate = @"1990/03/15";

    NSDate *todayDate = [NSDate date];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyy/MM/dd"];

    int time = [todayDate timeIntervalSinceDate:[dateFormatter dateFromString:birthDate]];

    int allDays = (((time/60)/60)/24);

    int days = allDays%365;

    int years = (allDays-days)/365;

    NSLog(@"You live since %i years and %i days",years,days);

OutPut :- You live since 25 years and 280 days