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 10 and built for iOS 12.

Open Xcode and create a new Single View App.

Display Date with Date Picker iOS Tutorial
Display Date with Date Picker iOS Tutorial

For product name, use IOSDatePickerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Display Date with Date Picker iOS Tutorial
Display Date with Date Picker iOS Tutorial

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. ". Next, drag a Date Picker below the label. Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

Display Date with Date Picker iOS Tutorial
Display Date with Date Picker iOS Tutorial

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

Display Date with Date Picker iOS Tutorial
Display Date with Date Picker iOS Tutorial

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

Display Date with Date Picker iOS Tutorial
Display Date with Date Picker iOS Tutorial

Ctrl-drag from the Date Picker to the ViewController class and create the following Action.

Display Date with Date Picker iOS Tutorial
Display Date with Date Picker iOS Tutorial

The Storyboard should look like this.

Display Date with Date Picker iOS Tutorial
Display Date with Date Picker iOS Tutorial

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 Runthe project, change the date and this date will be displayed on screen. 

Display Date with Date Picker iOS Tutorial
Display Date with Date Picker iOS Tutorial

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