iPhone UIDatePicker setMaximumDate

2019-05-11 18:09发布

问题:

I am trying to build a datepicker which has today as a minimum date and 1 Feb 2011 as Maximum date.

I have set the minimum date as followed

[picker setMinimumDate: [NSDate date]];

and this works just fine but the MaximumDate does not seem to be correct.

[picker setMaximumDate: [NSDate dateWithNaturalLanguageString:@"11/02/01"]];

How do I set the maximum date correctly?

回答1:

Found the answer. Thanks anyway for your help.

[picker setDatePickerMode:UIDatePickerModeDate];

NSDateFormatter* formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setLenient:YES];
[formatter1 setDateStyle:NSDateFormatterShortStyle];
[formatter1 setTimeStyle:NSDateFormatterShortStyle];

NSString* dateString = @"February 1 2011 10:00am";
NSDate* maxDate = [formatter1 dateFromString:dateString];

[picker setMinimumDate: [NSDate date]];
[picker setMaximumDate: maxDate];


回答2:

 NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
        NSDate *currentDate = [NSDate date];
        NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
        [comps setYear:0];
        NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
        [comps setYear:-5];
        NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

        [datePicker setMaximumDate:maxDate];
        [datePicker setMinimumDate:minDate];

hear showing date current date to minDate and five year(back) to maxDate it's show only five year.....



回答3:

You can also do it in Interface Builder's palette. I think if you press "Command-1" it will switch to a tab in the palette that allows you to set the Maximum date for the picker.