1

我想为 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])



        }
4

2 回答 2

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 你会得到这些日期之间的差异

于 2012-07-26T14:21:32.753 回答
-2

此代码应将 NSTimeInterval 转换为天数:

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

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

于 2012-07-26T14:13:31.557 回答