Sometimes we need of a date and time picker in our app to pick a date and time . Today I am going to demonstrate how to use Apple's inbuilt UIDatePicker to pick the date and time. It is very simple.
To use UIDatePicker in an app , first of all create a UIDatePicker instance and set mode as what we want to have in our picker, only date/time or both. As in my case I want to have both in my app . So i set the mode to UIDatePickerModeDateAndTime .
//create an instance of the NSDatePicker
UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame: CGRectZero];
//set mode
[datePicker setDatePickerMode:UIDatePickerModeDateAndTime];
Then add a selector to the date picker that will be called when user want to select the date and time from datePicker .
//add target
[datePicker addTarget:self action:@selector(selectDateAndTime:) forControlEvents:UIControlEventValueChanged];
Thats all, we have configured the datePicker. Now add the datePicker to the control when we want to datePicker to be appeared.
As I want datePicker to be appeared when user tap on a textField, So i add the datePicker to texField's accessory view as:
//add datePicker as accessory view of the textField:
self.txt_Time.inputView = datePicker ;
Now implement the method that we have assigned as a selector to datePicker:
-(void)selectDateAndTime:(UIDatePicker*)picker{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"hh:mm a dd-MM-yyyy "];
NSString *formattedString = [dateFormatter stringFromDate:[datePicker date]];
self.txt_time.text = formattedString;
}
That is it. How easy it is.