Display Date with Date Picker iOS Tutorial

The Date Picker provides a custom Picker View that uses multiple rotating wheels to allow an user to select dates and times. In this tutorial the selected date is presented onscreen inside a label. This tutorial is made with Xcode 8.2.1 and built for iOS 10.2.

Open Xcode and create a new Single View Application.

For product name, use IOS10DatePickerTutorial 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 and drag a Label to the main View. Double-click the Label and give it a title of "MM/DD/YY HH:MM.". Select the Align Auto Layout button in the bottom-right corner of the Storyboard. Tick the "Horizontally in Container" line,  Select "Items of New Constraints" in the Update Frames section and Select "Add 1 Constraint" 

Select the button and click the Pin Auto Layout button on the bottom-right of the Storyboard. Pin the button at the top edge and select "Items of New Constraints" at the Update Frames section. Select "Add 1 Constraint".

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl-drag or right-click-drag from the Label to the ViewController class and create the following Outlet.

Ctrl-drag or right-click-drag from the Date Picker to the ViewController class and create the following Outlet.

Ctrl-drag or right-click-drag from the Date Pikcer to the ViewController class and create the following Action.

The Storyboard should look like this.

Go to the ViewController.swift file and implement the datePickerChanged method

@IBAction func datePickerChanged(_ sender: Any) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = DateFormatter.Style.short
        dateFormatter.timeStyle = DateFormatter.Style.short
        let strDate = dateFormatter.string(from: 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 string(from:) method converts the Date 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 IOS10DatePickerTutorial at the ioscreator repository on github.