Reputation: 228
I got an issue in trying to limit the date. With setting the date like that self.datePicker.maximumDate = [NSDate date];
it is only grey the date after now but enable the user to select a date after this maximum date.
So When the picker value changed I compare the selected date if up than the current date I edit it.
If I use both solutions I got weird behaviour, any idea ?
- (IBAction)pickerValueChanged:(id)sender {
dispatch_async(dispatch_get_main_queue(), ^{
UIDatePicker *datePicker = (UIDatePicker *)sender;
if ([self.datePicker.date compare:[NSDate date]] == NSOrderedDescending) {
datePicker.date = [NSDate date];
}
});
}
This function is triggered when the date value from the date picker did change. If I set a minimum and a maximum date I got a weird behaviour. Any idea?
EDIT:
self.datePicker.maximumDate = [NSDate date];
Upvotes: 1
Views: 11142
Reputation: 796
Either you can set the maximum date in xcode or programatically.
1.Programatically you can set the picker maximum date by using the below line of code.
[self.yourPickerView setMaximumDate: [NSDate date]];
This line of code will set the current date as maximum date that can select in picker.
Upvotes: 4
Reputation: 89
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = [NSDate date];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:currentDate];
NSInteger year = [components year];
NSDateFormatter* formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:@"yyyy-MM-dd"];
NSString *dateString = [NSString stringWithFormat:@"%ld-12-31",(long)year];
NSDate *maxDate = [formatter1 dateFromString:dateString];
[self.dobPickerView setMaximumDate: maxDate];
Upvotes: -1
Reputation: 67
- (IBAction) datePickerChanged:(id)sender {
// When `setDate:` is called, if the passed date argument exactly matches the Picker's date property's value, the Picker will do nothing. So, offset the passed date argument by one second, ensuring the Picker scrolls every time.
NSDate* oneSecondAfterPickersDate = [picker.date dateByAddingTimeInterval:1] ;
if ( [picker.date compare:picker.minimumDate] == NSOrderedSame ) {
NSLog(@"date is at or below the minimum") ;
picker.date = oneSecondAfterPickersDate ;
}
else if ( [picker.date compare:picker.maximumDate] == NSOrderedSame ) {
NSLog(@"date is at or above the maximum") ;
picker.date = oneSecondAfterPickersDate ;
}
}
Upvotes: -1
Reputation: 1760
Yes, you can set minimum and maximum date, using .xib and picker settings
Upvotes: 2
Reputation: 1253
Yes you can set Maximum date and minimum date to UIDatePickerView
Below is the another stackover flow link
UIDatePicker, setting maximum and minimum dates based on todays date
Upvotes: 1