user1851782 user1851782 - 6 months ago 29
iOS Question

How to compute age from NSDate

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
?

Answer
- (NSInteger)ageFromBirthday:(NSDate *)birthdate {
    NSDate *today = [NSDate date];
    NSDateComponents *ageComponents = [[NSCalendar currentCalendar]
                                       components:NSCalendarUnitYear
                                       fromDate:birthdate
                                       toDate:today
                                       options:0];
    return ageComponents.year;
}

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.