如何在 iOS 中进行年龄验证?

How to give age validation in iOS?

已经创建了以下用于年龄验证的函数,但它没有给我正确的结果。有人知道怎么做吗?

尝试了一些其他代码,但被删除了。我的应用目标是 iOS 7 及更高版本。

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

我觉得你的代码很完美!

在我看来问题出在您的 _txtBirthDate.text 格式上。它应该在 yyyy-MM-dd

我 运行 你的代码用静态字符串值代替 _txtBirthDate.text 并得到了完美的结果。检查以下代码供您参考。

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

输出:

- You live since 25 years and 280 days

您应该使用 NSCalendar API 来获取特定日期之间的日期分量数。

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

您不能依赖假设一年有 365 天(考虑闰年)。此外,一天的持续时间并不总是 24 小时(考虑夏令时的变化)。这可能会给您的计算带来错误。 NSCalendar 正确处理所有这些东西。