Displaying Date with Date Picker in iOS7

The Date Picker in iOS7 provides an custom Picker View that uses multiple rotating wheels to allow users to select dates and times. In this tutorial we will display the selected date of the Date Picker to the screen.

Update: August 14, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

Open Xcode and create a new Single View Application. For product name, use iOS7DatePickerTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices. 

Go the Storyboard and drag a label to the main view, also drag a Date Picker to the main view and center it. The Storyboard should look like this.

Select the Assistant Editor and open ViewController.m. Ctrl and drag from the label to the @interface section and create the following outlet.

Repeat this step with the Date Picker to create the following outlet 

In ViewController.m add the following line to the end of viewDidLoad

[self.myDatePicker addTarget:self action:@selector(datePickerChanged:) forControlEvents:UIControlEventValueChanged];

When the date is changed by the user a UIControlEventValueChanged event is triggered and the datePickerChanged method is called. Let's add this method.

- (void)datePickerChanged:(UIDatePicker *)datePicker
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm"];
NSString *strDate = [dateFormatter stringFromDate:datePicker.date];
self.selectedDate.text = strDate;

The dateFormatter formats the date so it will display nicely on our label. The stringFromDate function converts the NSDate object to an NSString. This string is assigned to the text property of our label. Build and Run the project, change the date and this date will be displayed on screen. 

You can download the source code of the iOS7DatePickerTutorial at the ioscreator repository on github.