4 Answers4

0

You can set the minimum and maximum date properties of your UIDatePicker view.

You can create the dates using NSDateComponents, and just set the Hour and Minute components.

This won't show a popup, but the user will not be able to select an invalid date. (Which is the recommended behavior).

To check if the date in the input field is valid, you can use the NSDate comparison methods agains your min and max dates.

Pandafox
  • 564
  • 1
  • 5
  • 18
0

u can use this function to check selected date (date) is in range (begindate - enddate)

- (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
    return ([date compare:beginDate] == NSOrderedAscending) && ([date compare:endDate] == NSOrderedDescending)
}

for Swift :

extension NSDate
{
    func isBetweenDates(beginDate: NSDate, endDate: NSDate) -> Bool
    {
        return self.compare(beginDate) == .OrderedAscending && self.compare(endDate) == .OrderedDescending
    }
}
Tim Vermeulen
  • 12,352
  • 9
  • 44
  • 63
0

You can follow the suggestion in Pandafox's answer, set minimumDate and maximumDate of your UIDatePicker. Or answer your question

As two other answer's shown are not given in Swift, I will try with the following.

First, you need to set your picker to listen the control event

// Add this in viewDidLoad
datePicker.addTarget(self, action: "changedAction", forControlEvents: UIControlEvents.ValueChanged)

Then in the action, get the value, check within range, and show alert if needed.

func changedAction() {
    var datePicked = datePicker.date

    if datePicked.isGreaterThanDate(endDate) && datePicked.isLessThanDate(startDate) {
        // show alert
        let alertController = UIAlertController(title: "Warning", message: "Date picked out of range", preferredStyle: UIAlertControllerStyle.Alert)
        alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))

        self.presentViewController(alertController, animated: true, completion: nil)
    }
}

Use extension methods to compare dates, check more here

extension NSDate {
func isGreaterThanDate(dateToCompare: NSDate) -> Bool {
    return self.compare(dateToCompare) == NSComparisonResult.OrderedDescending
}

func isLessThanDate(dateToCompare: NSDate) -> Bool {
    return self.compare(dateToCompare) == NSComparisonResult.OrderedAscending
}
Community
  • 1
  • 1
zc246
  • 1,514
  • 16
  • 28
0

you can check like this

- (void)viewDidLoad 
{
    [super viewDidLoad];
    UIDatePicker* picker = [[UIDatePicker alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:picker];
    picker.datePickerMode = UIDatePickerModeTime;
    [picker addTarget:self action:@selector(pickerAction:) forControlEvents:UIControlEventValueChanged];
}

- (void)pickerAction:(UIDatePicker*)picker
{
    // do something such as check if the picker.data is valid
    NSLog(@"pickerAction %@",picker.date);
}
joy
  • 1