本文介绍了如何从NSDate计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作一个应用程序,需要根据他们的生日找到某人的年龄。我有一个简单的 NSDate
但我如何用 NSDateFormatter
找到它?
I am working on an app that needs to find someones age depending on their birthday. I have a simple NSDate
but how would I find this with NSDateFormatter
?
推荐答案
- (NSInteger)ageFromBirthday:(NSDate *)birthdate {
NSDate *today = [NSDate date];
NSDateComponents *ageComponents = [[NSCalendar currentCalendar]
components:NSCalendarUnitYear
fromDate:birthdate
toDate:today
options:0];
return ageComponents.year;
}
NSDateFormatter
适用于格式化日期(呃!)。根据经验,只要您需要在 NSDate
上执行某些计算,就可以使用 NSCalendar
和相关联的类,例如 NSDateComponents
。
NSDateFormatter
is for formatting dates (duh!). As a rule of thumb, whenever you need to perform some computation on an NSDate
you use a NSCalendar
and associated classes, such as NSDateComponents
.
这篇关于如何从NSDate计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!