Aarti Oza
Aarti Oza

Reputation: 1154

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;
    }
}

Upvotes: 0

Views: 1254

Answers (2)

Andriy
Andriy

Reputation: 2796

You should use NSCalendar API to get the number of date components between particular dates.

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear | NSCalendarUnitDay fromDate:birthDate toDay:[NSDate date] options:0];
NSLog(@"You live since %i years and %i days", components.year, components.day);

You can't rely on the assumption that year has 365 days(consider leap years). Also, the day duration is not always 24 hours(consider DST changes). It could bring errors in your calculations. NSCalendar handles all this stuff correctly.

Upvotes: 2

iGatiTech
iGatiTech

Reputation: 2268

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

Upvotes: 3

Related Questions