Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 5 - Setting UIDatePicker minimum date to "today"

I know how to set the maximum and minimum date in a UIDatePicker to a certain date, put I was wondering if it would be possible to make it so the minimum date is always the "today" date. It just doesn't make sense in my app for users to enter a date that's in the past, just for them to add one that is today or in the future.

like image 298
mhbdr Avatar asked Jun 13 '12 17:06

mhbdr


1 Answers

set the minimum date to now and the displayed date to now + 2 secs:

myDatePicker.date = 
       [[ NSDate alloc ] initWithTimeIntervalSinceNow: (NSTimeInterval) 2 ];
myDatePicker.minimumDate = 
       [[ NSDate alloc ] initWithTimeIntervalSinceNow: (NSTimeInterval) 0 ];

Do this when you either init the Nib or set the data for the view controller on re-use. You may also do this in viewWillAppear.

Extra points: You may add a IBAction method that subtly encourages the user not to pick an ill advised date:

- (IBAction)datePickerChanged: (id)sender
{
     if ( [ datePicker.date timeIntervalSinceNow ] < 0 )
         datePicker.date = now;
}
like image 167
gjpc Avatar answered Nov 23 '22 18:11

gjpc