从生日得到年龄

从�生日(需要符合日期格式)得到年龄:

- (NSInteger)ageWithBirthdayString:(NSString *)birthdayString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:DATEFORMATTERSTRING];

    NSDate *birthday = [formatter dateFromString:birthdayString];
    NSDate *now = [NSDate date];

    NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                       components:NSCalendarUnitYear
                                       fromDate:birthday
                                       toDate:now
                                       options:0];
    NSInteger age = [ageComponents year];

    return age;
}

你可能感兴趣的:(从生日得到年龄)