For a recent project, I needed to get the user’s age within my iPhone application. It was a simple “how old are you?” question. Here’s the quick snippet for how I went about getting that info.
What you’ll already need is either:
- a UIPickerView object created, initialized, and set in your view controller; or
- a UIPickerView created and attached using Interface Builder.
In this example, I’m using the variable name pickerView for my UIPickerView object.
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[[self pickerView] date] toDate:[NSDate date] options:0];
NSInteger years = [components year];
NSLog(@"User is %d years old", years);
That’s it! How accurate it is depends entirely on Apple’s implementation. You can also do the same for any of the calendar values listed in the NSLocale documentation.