views:

28

answers:

1

I have to prompt users for choosing a date from a CoCoa UIDatePicker but avoiding him to select sundays ans saturdays, since my goal is to make them select a date for an appointment

The best way should be disabling that dates, in the same way of minimumDate property, but I was not able to find how to do that

A: 

You could do something like this:

UIDatePicker *datePicker = [[UIDatePicker alloc] init];
[datePicker addTarget:self action:@selector(dateChanged:) forControlEvent:UIControlEventValueChanged];

Implementation for dateChanged:

- (void)dateChanged:(id)sender {
  UIDatePicker *datePicker = (UIDatePicker *)sender;
  NSDate *pickedDate = datePicker.date;

  NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:pickedDate];
  NSInteger weekday = [weekdayComponents weekday];
  [gregorian release];

  if (weekday == 1 || weekday == 7) { // Sunday or Saturday
    NSDate *nextMonday = nil;
    if (weekday == 1)
      nextMonday = [pickedDate dateByAddingTimeInterval:24 * 60 * 60]; // Add 24 hours
    else
      nextMonday = [pickedDate dateByAddingTimeInterval:2 * 24 * 60 * 60]; // Add two days

    [datePicker setDate:nextMonday animated:YES];

    return;
  }

  // Do something else if the picked date was NOT on Saturday or Sunday.
}

This way, when a date is picked that is either on a Saturday or Sunday, the date picker automatically selects the Monday after the weekend.

(Code untested!)

Douwe Maan