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

时间:2015-12-14 05:28:54

标签: ios objective-c nsdate

为年龄验证创建了以下功能,但它没有让我正确。有谁知道怎么做?

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

  

选定日期 - 13/03/1990输出

     

你的生活时间是-68岁和-35天

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

2 个答案:

答案 0 :(得分:3)

您的代码看起来很完美!

我觉得问题在于你的_txtBirthDate.text格式。应该是yyyy-MM-dd

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

    primaryStage.setTitle("Sierpinski Triangle ");
    primaryStage.setScene(scene);
    primaryStage.setResizable(false);
    primaryStage.show();
  }

  private Color getRandomColor() {
    Random randomGenerator = new Random();
    int red   = randomGenerator.nextInt(256);
    int green = randomGenerator.nextInt(256);
    int blue  = randomGenerator.nextInt(256);
    return Color.rgb(red,green,blue);
  }

  private Vertex getRandomVertex(){
    Random randomGenerator = new Random();
    int vertexIndex = randomGenerator.nextInt(cornerVertexArray.length);
    return cornerVertexArray[vertexIndex];
  }
}

输出:

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

答案 1 :(得分:2)

您应该使用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小时(考虑DST变化)。这可能会给您的计算带来错误。 NSCalendar正确处理所有这些内容。