Alex Alex - 18 days ago 6
iOS Question

Can't set the minimum date in uidatepicker

I went through many questions and answers here in stack over flow about setting the minimum date in UIDatepicker, I have tried most of it but I am still not able to set the minimum date in UIDatepicker. My exact requirement is that for people who are aged above 70 should not sign up with my app. This is the code which I have tried but didn't give me the exact result.

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = [NSDate date];

NSDateComponents *comps = [[NSDateComponents alloc] init];
NSDateComponents *compsII = [[NSDateComponents alloc] init];
[comps setYear:-14];

NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[compsII setYear:1960];

NSDate *minDate = [[NSCalendar currentCalendar] dateFromComponents:compsII];

datePicker =[[UIDatePicker alloc]initWithFrame:CGRectMake(0, 400, self.view.frame.size.width, 200)];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.hidden=NO;
datePicker.maximumDate = maxDate;
datePicker.minimumDate = minDate;

Answer

I think this is your problem

  1. You have your min and max dates the wrong way around.
  2. You have set the year to -14.

Update:

Try this code:

NSDate *todaysDate = [NSDate date];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *minDateComponents = [[NSDateComponents alloc] init];
[minDateComponents setYear:-70];
NSDate *minDate = [gregorian dateByAddingComponents:minDateComponents toDate:todaysDate  options:0];

NSDateComponents *maxDateComponents = [[NSDateComponents alloc] init];
[maxDateComponents setYear:-14];
NSDate *maxDate = [gregorian dateByAddingComponents:maxDateComponents toDate:todaysDate  options:0];
Comments