Search code examples
iphonensdatenscalendar

How to check if NSDate chosen by user occured some years ago?


In my application I need to check if user turned 18. I provide UIDatePickerView for him and he selects his birthday date. I store it in the NSDate field. How to check if 18 years has passed already since his birthday?


Solution

  • [[[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:birthDate toDate:[NSDate date] options:0] year]
    

    or as Jonathan Grynspan pointed out, this would be better:

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    int years = [[gregorian components:NSYearCalendarUnit fromDate:birthDate toDate:[NSDate date] options:0] year];
    [gregorian release];
    

    and now with ARC it can be (overly) brief:

    int years = [[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] components:NSYearCalendarUnit fromDate:birthDate toDate:[NSDate date] options:0] year];