Getting MAX_INT from NSDateComponents
I'm trying to write my first iPhone app, and I'm using a date picker object for the user to enter their date of birth. Part of my app requires the year in int format. I've added the code as below. What's odd is that 'month' gets the right value. But day and year seem to be stuck at MAX_INT (2147483647). Can anyone tell me what I'm doing wrong?
-(IBAction)dateOfBirthChanged:(id)sender {
NSCalendar* calender = [NS开发者_StackOverflow中文版Calendar currentCalendar];
NSDateComponents* dateComponents = [calender components:NSMonthCalendarUnit fromDate:[datepicker date]];
NSInteger day = [dateComponents day];
NSInteger month = [dateComponents month];
NSInteger year = [dateComponents year];
label.text = [NSString stringWithFormat:@"Your year of birth is %d", year];
}
Try this instead:
NSDateComponents *dateComponents = [calender components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[datepicker date]];
Ref: -components:fromDate:
精彩评论