如何根据NSDate计算年龄 [英] How to calculate the age based on NSDate
本文介绍了如何根据NSDate计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据此格式的出生日期计算年龄6/24/1976 mon / date / year ...
how to calculate the age based on the birth date in this format 6/24/1976 mon/date/year...
推荐答案
许多这些答案并没有适用于闰年,所以最好是使用苹果的方法,而不是除以常数。
Many of these answers don't properly account for leap years and such, best is to use Apple's methods instead of dividing by constants.
NSDate* birthday = ...;
NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSCalendarUnitYear
fromDate:birthday
toDate:now
options:0];
NSInteger age = [ageComponents year];
我认为这比这里的任何其他答案更干净,更准确。
I think this is cleaner and more accurate than any of the other answers here.
这篇关于如何根据NSDate计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文