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

标签 iphone nsdate nscalendar

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

最佳答案

[[[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];

关于iphone - 如何检查用户选择的 NSDate 是否发生在几年前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5144085/

相关文章:

ios - 如何将 dateFormatter 值(例如 2019 年 7 月 7 日)从时间戳转换为 2019 年 7 月 7 日?

iphone - 如何获取 iPhone 的系统日期

xcode - Swift - 检查日期是否在下周/下月。 ( isDateInNextWeek() isDateInNextMonth() )

ios - 捕获当前时间但将分钟重置为零而不处理时区

iphone - iPhone SDK 中的 Tell-A-Friend 形式

iOS 8 建议的应用程序图标锁屏

iphone - 获取 pdf 文件的页码 Titanium Studio iPhone

iphone - UISegmentedControl 委托(delegate)/触摸事件

ios - NSDate 总是显示相同的日期

swift - 设置所有标志的 NSCalendarUnit 标志