23

How to hide the future dates in UIDatePicker for user choosing only past and current year of birthdays.

I search lot of source but I can't get the desired result.

Here is my code,

 dateofBirthDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];

    dateofBirthDatePicker.datePickerMode = UIDatePickerModeDate;
    [dateofBirthDatePicker setBackgroundColor:DATE_PICKER_GRAY_COLOR];

//    UILabel *label = [UILabel appearanceWhenContainedIn:[UITableView class],[UIDatePicker class], nil];
//    label.font = HELVETICA_NEUE(24);
//    label.textColor = GREEN_COLOR;
    [dateofBirthDatePicker addTarget:self
                              action:@selector(LabelChange:)
                    forControlEvents:UIControlEventValueChanged];
    dateofbirthTextField.inputView = dateofBirthDatePicker;
    [self datePickerToolBar];
}

- (void)LabelChange:(id)sender
{
    NSDateFormatter *dateFormat= [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd/MM/yyyy"];
    dateofbirthTextField.text = [NSString stringWithFormat:@"%@",
                                [dateFormat stringFromDate:dateofBirthDatePicker.date]];
}

If any body know the solution kindly give the suggestion. I really appreciate to you.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ram
  • 764
  • 1
  • 7
  • 20

5 Answers5

65

Here is the simple code to prevent future date selection:

dateofBirthDatePicker.maximumDate=[NSDate date];

In Swift :

dateofBirthDatePicker.maximumDate = Date()
Sharad Chauhan
  • 4,821
  • 2
  • 25
  • 50
Mawoon
  • 1,045
  • 1
  • 7
  • 10
14

In Swift 2:

self.datePicker.maximumDate = NSDate()

In Swift 3:

self.datePicker.maximumDate = Date()

Phil Hudson
  • 3,819
  • 8
  • 35
  • 59
9

In Swift 4.0.3 Xcode 9

Hide Future Date

self.picker.maximumDate = Date()
Bugs
  • 4,491
  • 9
  • 32
  • 41
Keshav Gera
  • 10,807
  • 1
  • 75
  • 53
3

You can use setMaximumDate: and setMinimumDate: on UIDatePicker object:

[dateofBirthDatePicker setMaximumDate:[NSDate date]]; // The max date will be today

// Optional you can set up min date as well
[dateofBirthDatePicker setMinimumDate:yourMinDate];
Greg
  • 25,317
  • 6
  • 53
  • 62
0
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1];
NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[comps setYear:-30];
NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

[datePicker setMaximumDate:maxDate];
[datePicker setMinimumDate:minDate];
Pancho
  • 4,099
  • 1
  • 21
  • 32