gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:30:02 25 4
gpt4 key购买 nike

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

尝试了一些其他代码,但它被贬低了。我的应用目标是 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

关于ios - 如何在 iOS 中进行年龄验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34260336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com