用户输入的年龄验证

时间:2012-07-26 14:01:45

标签: ios

我想为iOS创建一个年龄验证系统

我有一个用户通过UITextField输入的日期。如何将此日期与当前日期进行比较,以确定用户是否未满18岁。

这是我到目前为止所做的事情,但只是在几年内,即使今天的出生年份= 18岁,人们的年龄也可能低于18岁;

 NSArray *ageArray = [ageString componentsSeparatedByString:@"/"];

    int day = [[ageArray objectAtIndex:0] intValue];
    int month = [[ageArray objectAtIndex:1] intValue];
    int year = [[ageArray objectAtIndex:2] intValue];

    if(day <= 31 && month <= 12){

        NSDateFormatter* df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"MM/dd/yyyy"];
        NSDate* userDate = [df dateFromString:ageString];


        NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:userDate];
        NSDateComponents *today = [[NSCalendar currentCalendar] components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];

        NSLog(@"%d - %d\n%d", [today year], [otherDay year], ([today year] - [otherDay year]));

        if([today year] - [otherDay year] =< 18) {
            NSLog(@"too young");

            if([today month] < [otherDay month])



        }

2 个答案:

答案 0 :(得分:0)

你可以这样做:

NSDate *dateA = [NSDate date];
NSDate *dateB = [NSDate date]; //User's age

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                               fromDate:dateA
                                                 toDate:dateB
                                                options:0];

NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);

if (components.year < 18) {
    //Under Age
} else {
    //Ok Age
}

在NSLog中,您将获得这些日期之间的差异

答案 1 :(得分:-2)

此代码应将NSTimeInterval转换为days:

NSTimeInterval time = [enteredDate timeIntervalSinceDate:currentDate];
NSInteger days  = time/60/60/24;

然后您可以使用它来比较设定的天数。