Search code examples
iosuidatepicker

Reset MinimumDate in iOS UIDatePicker


I have 2 UIDatePickers, one set in UIDatePickerModeDate and the other in UIDatePickerModeTime.

If the first one has its date set to today, then the second one must have a restriction such that the user cannot select a time that is before now. To do this I use the setMinimumDate function. However, if the user sets a date in the future, I need to reset the minimumDate property, meaning that there should be no minimumDate set on the picker.

I am able to achieve this by calling

 [self.timePicker setMinimumDate:nil];

But this gives me an exception in the Xcode console output as below.

-[__NSCFCalendar components:fromDate:]: date cannot be nil
Future exception.
A few of these errors are going to be reported with this complaint, then further violations will simply be ignored.

How can I remove the minimumDate property of my timePicker after it has been set, without this exception being raised?
Thank you.

EDIT: The reason I tried setting it to nil was because Apple's documentation says that the default value of the minimumDate property is nil (here).

Also, I did try to set the minimum date to the future date selected by the user, after making the time component zero. This causes the time to be selected as 12 AM in the picker which is acceptable. Now if the user selects today's date again, nothing happens when I set the minimumDate property, i.e. I cannot toggle the minimumDate using this. The code is as follows:

(void)setMinimumDateForTimePicker {
 if([[NSCalendar currentCalendar] isDateInToday:self.datePicker.date]) {
      NSLog(@"Min date for today");
      [self.timePicker setMinimumDate:[self roundUpToNearestFifteenMinutes:[NSDate date]]];
 } else {
     // date is in the future so zero out time
     NSLog(@"Min date for the future");
     NSDateComponents* selectedDateWithZeroTime = [[NSCalendar currentCalendar] components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.datePicker.date];
 [self.timePicker setMinimumDate:[[NSCalendar currentCalendar] dateFromComponents:selectedDateWithZeroTime]];
 }
 [self updateStartTimeField:nil];

}

Solution

  • This is the code that worked finally for what I was trying to do.

    - (void)setMinimumDateForTimePicker {
        if([[NSCalendar currentCalendar] isDateInToday:self.datePicker.date]) {
            [self.timePicker setMinimumDate:[self roundUpToNearestFifteenMinutes:[NSDate date]]];
        } else {
            [self.timePicker setMinimumDate:[[NSCalendar currentCalendar] startOfDayForDate:[NSDate date]]];
        }
        [self updateStartTimeField:nil];
    }