views:

517

answers:

1

Need a UIDatePicker with specific maximum and minimum dates and times. Currently NSDatePicker.minimumDate and .maximumDate appear to only consider the date. What's the proper way to handle this?

+1  A: 

NSDates contain both the date and the time. From the docs:

NSDate objects represent a single point in time.

The example below has the current date and time as the minimum value and the time an hour from now as the maximum value (to test it just drop it into the viewDidLoad of any UIViewController):

// Time right now
NSDate *minDate = [NSDate new];
// One hour from now
NSDate *maxDate = [[NSDate alloc] initWithTimeIntervalSinceNow:60*60];

UIDatePicker *picker = [UIDatePicker new];
[picker setDatePickerMode:UIDatePickerModeDateAndTime];
[picker setMinimumDate:minDate];
[picker setMaximumDate:maxDate];
[[self view] addSubview:picker];
[super viewDidLoad];

You can read more about NSDate on the Dev Center.

Paulo Fierro
Thank you Paulo. Yes, I'm aware of the above and my mindate and maxdate NSDate objects contain the time but the UIDatePicker is only setting the boundaries by the date. In other words, if I set mindate to today's date at 8am it prevents me from setting the date to yesterday but I can still pick an earlier time...6am for instance.
Greypoint
That's very strange. If you change minDate to an NSDate a few hours earlier you should not be able to pick an earlier time. What happens in my case when I pick 6 am is that the picker animates back to the minimum valid time 8 am. Do you have a code sample?
Paulo Fierro
Well I'm happy to hear it works the way I think it should. I'm unhappy to think I have a problem in my code :) Let me review it and see if I can pull a relevant sample out. Thanks for your continued help.
Greypoint