通过出生年月日计算年龄
NSString *birth = @"1993-03-03";
// 通过NSDateFormatter将NSString 转换成 NSDate 格式
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:birth];
// 通过NSDateComponents 从 date 中提取出 年月日
创建并初始化一个NSDateComponents实例components1,并从指定的时间开始分别提取年、月、日、小时、分钟和秒的分量
NSInteger year = [components1 year];
NSInteger month = [components1 month];
NSInteger day = [components1 day];
NSInteger hour = [components1 hour];
NSInteger minute = [components1 minute];
NSInteger second = [components1 second];
// 获取系统当前的年月日
NSDate *currentDate = [NSDate date]; // 获得系统的时间
The NSDateComponents object named components2 has been created by extracting specific calendar components from the current calendar instance, starting from the current date. The calendar components include year, month, day, hour, minute and second.
NSInteger currentYear = [components2 year];
NSInteger currentMonth = [components2 month];
NSInteger currentDay = [components2 day];
// 计算年龄
NSInteger iAge = currentYear - year - 1;
if ((currentMonth > month) || (currentMonth == month && currentDay >= day)) {
iAge++;
}
