Displaying Date with Date Picker in iOS8 with Swift

The Date Picker in iOS 8 provides an custom Picker View that uses multiple rotating wheels to allow users to select dates and times. In this tutorial the current selected date is presented onscreen inside a label. This tutorial is written in Swift so you will need Xcode 6. It can be downloaded at Apple's developer portal.

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftDatePickerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the storyboard. In Xcode 6 view controllers are now square by default, so that you can create one user interface use just for multiple devices. In iOS8 you can layout the storyboard using constraints and size classes. Since this app is only going to be for the iPhone, you can disable size classes. In the File Inspector untick Use Size Classes.

Choose Keep size class data for: iPhone, and click Disable Size Classes.

Drag a Label to the View Controller change the Label text to MM/DD/YY HH:MM. Nextdrag a Date Picker to the View Controller and center it. The Storyboard should look like this.

Select the Assistant Editor and open ViewController.swift. Ctrl and drag from the Label to the ViewController class and create the following outlet.

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

Add the following line to the end of viewDidLoad

datePicker.addTarget(self, action: Selector("dataPickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)

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

func datePickerChanged(datePicker:UIDatePicker) {
  var dateFormatter = NSDateFormatter()
  dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
  dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
  var strDate = dateFormatter.stringFromDate(datePicker.date)
  dateLabel.text = strDate

The dateFormatter formats the date in Short Style which displays the date and time as MM/DD/YY HH:MM on the dateLabel. The stringFromDate method converts the NSDate object to a String. 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  iOS8SwiftDatePickerTutorial at the ioscreator repository on github.