如何检查用户选择的 NSDate 是否发生在几年前?

发布于 2024-10-19 14:28:38 字数 107 浏览 3 评论 0原文

在我的应用程序中,我需要检查用户是否年满 18 岁。我为他提供 UIDatePickerView,然后他选择他的生日日期。我将它存储在 NSDate 字段中。 如何查看自己的生日是否已经过去18年了?

In my application I need to check if user turned 18. I provide UIDatePickerView for him and he selects his birthday date. I store it in the NSDate field.
How to check if 18 years has passed already since his birthday?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寒江雪… 2024-10-26 14:28:38
[[[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:birthDate toDate:[NSDate date] options:0] year]

或者正如 Jonathan Grynspan 指出的那样,这会更好:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int years = [[gregorian components:NSYearCalendarUnit fromDate:birthDate toDate:[NSDate date] options:0] year];
[gregorian release];

现在有了 ARC,它可以(过于)简短:

int years = [[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] components:NSYearCalendarUnit fromDate:birthDate toDate:[NSDate date] options:0] year];
[[[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:birthDate toDate:[NSDate date] options:0] year]

or as Jonathan Grynspan pointed out, this would be better:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int years = [[gregorian components:NSYearCalendarUnit fromDate:birthDate toDate:[NSDate date] options:0] year];
[gregorian release];

and now with ARC it can be (overly) brief:

int years = [[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] components:NSYearCalendarUnit fromDate:birthDate toDate:[NSDate date] options:0] year];
ま柒月 2024-10-26 14:28:38

应该这样做:

    NSTimeInterval interval = [birthday timeIntervalSinceNow];

if (interval > 18*365*24*60*60) {
    NSLog(@"You're more than 18");
}

It should be done with something like that:

    NSTimeInterval interval = [birthday timeIntervalSinceNow];

if (interval > 18*365*24*60*60) {
    NSLog(@"You're more than 18");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文