Getting Started with the UIDatePicker for iOS Using Swift


  • Share on Pinterest

The UIDatePicker is used for selecting a date, shocking right! Many applications use it and I am going to show you how you can too using Swift. In fact the UIDatePicker is just a UIPickerView that comes with customizable dates and times packed in for you. Not familiar with the UIPickerView? Then I have an article on getting started with one, just click this link.

Let's take a look at getting started with some basic usage ideas for a UIDatePicker object.

It will come as no surprise then that much of what you learned about the UIPickerView applies to UIDatePicker.

Set Up

First create a new Swift based Single View Application iOS project, this simple project is all we need to start playing with the UIDatePicker.

Now in the Object Library search for ‘date' and you should see the Date Picker. Drag it on to the main storyboard, positioning really does not matter however I placed it in the center leaving space above and below for other controls.

Storyboard with UIDatePicker Object in Center

At this point you could in fact run the application either on a device or the simulator and you will see the date picker appear on the screen showing today's date, but that is not going to get you very far is it!

iPhone 4s - Simulator showing date selector

Grab the date and show it

Time to start having some fun, how about something simple like a button that grabs the selected date and displays it in a label?

Add a button and label to the storyboard along with an @IBOutlet and @IBAction for them in the controller. At this point I hope you are thinking we also need an @IBOutlet for the date picker, because we do :). These should be normal things to do by now but if not see some of my other articles on my [Getting Started with Swift] page to brush up on the basics.

An extra step for convenience, select the view controller on the story board and go to the menu and select Editor > Resolve Auto Layout Issues > Add Missing Constraints this will add the needed constraints to just keep everything nicely displayed when you run the app.

Storyboard with Date, Label and Button Objects

Before we go any further, here is the entire contents of my view controller for those playing catch up!

//
//  ViewController.swift
//  DatePickerExample
//
//  Created by Peter Witham on 8/15/15.
//  Copyright © 2015 Peter Witham. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var datePicker: UIDatePicker!
    @IBOutlet weak var lblDisplayDate: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func btnGetDate(sender: UIButton) {
    }

}

Coding Time!

Now all the layout is done we will turn to filling in the missing code. So here is what we need to make happen, when the button is pressed we need to get the currently selected date from the UIDatePicker. This date cannot just be displayed as a string, we need to format it first using a simple NSDateFormatter. Then we will send that string to the label for display.

Depending on how you named the outlets and action you may need to change the code below, this is the code with comments on my button @IBAction

 @IBAction func btnDisplayDate(sender: UIButton) {
    // First we need to create a new instance of the NSDateFormatter
    let dateFormatter = NSDateFormatter()
    // Now we specify the display format, e.g. "27-08-2015
    dateFormatter.dateFormat = "dd-MM-YYYY"
    // Now we get the date from the UIDatePicker and convert it to a string
    let strDate = dateFormatter.stringFromDate(datePicker.date)
    // Finally we set the text of the label to our new string with the date
    lblDisplayDate.text = strDate
 }

At this point you can run the application and it should work as expected, choose a date and touch the button to display it formatted on the label.

iPhone 4s - Simulator showing selected date

A couple of notes for those new to the NSDateFormatter:

To display any kind of date we first need to format it, you may of noticed if you dared to try just doing something like

 lblDisplayDate.text = datePicker.date

That the compiler gave you a hard time by saying it cannot convert the date to a string. There are reasons for that, without formatting first, the date (and time) are rather complicated as anyone with a computer science background will love to tell you.

So to get around this problem and throw dates/times around like balloons at a party we need a way to control how they are formatted, that's where NSDateFormatter comes in. You can read the [Apple documentation on NSDateFormatter at this link].

Setting the Date with Code (or Making a Date with Swift)

So how about if we want to set the NSDatePicker to a specific date using code?

Add another button with an @IBAction, for this next part I take no credit. I found an excellent way to make creating a new NSDate object simple on stackoverflow.com, thanks to this post response by algal that suggests creating an extension to NSDate.

So after the closing class curly brace in the view controller add the following code

extension NSDate
{
    convenience
      init(dateString:String) {
      let dateStringFormatter = NSDateFormatter()
      dateStringFormatter.dateFormat = "yyyy-MM-dd"
      dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
      let d = dateStringFormatter.dateFromString(dateString)!
      self.init(timeInterval:0, sinceDate:d)
    }
}

Thanks to this great code we can now set the datePicker.date by adding two lines to our @IBAction we created

@IBAction func btnSetDate(sender: UIButton) {
    let newDate = NSDate(dateString:"2015-12-25”)
    datePicker.date = newDate
}

Here is an image of the new button and all the code so far for reference.

Xcode with storyboard and view controller

Go ahead and run the application, touch the new button and the date should now change to the new one with a nice animation thrown in for us! Do not forget it’s now Christmas, where is my present? (I’ll settle for a social share of this post instead).

iPhone 4s - Simulator showing UIDatePicker and 12-25-2015

If you had any problems or you are just curious, here is the entire code for the ViewController.swift

//
//  ViewController.swift
//  DatePickerExample
//
//  Created by Peter Witham on 8/15/15.
//  Copyright © 2015 Peter Witham. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var datePicker: UIDatePicker!
    @IBOutlet weak var lblDisplayDate: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func btnGetDate(sender: UIButton) {
        // First we need to create a new instance of the NSDateFormatter
        let dateFormatter = NSDateFormatter()
        // Now we specify the display format, e.g. "27-08-2015
        dateFormatter.dateFormat = "dd-MM-YYYY"
        // Now we get the date from the UIDatePicker and convert it to a string
        let strDate = dateFormatter.stringFromDate(datePicker.date)
        // Finally we set the text of the label to our new string with the date
        lblDisplayDate.text = strDate
    }

    @IBAction func btnSetDate(sender: UIButton) {
        let newDate = NSDate(dateString:"2015-12-25")
        datePicker.date = newDate
    }
}

extension NSDate
{
    convenience
    init(dateString:String) {
        let dateStringFormatter = NSDateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        let d = dateStringFormatter.dateFromString(dateString)!
        self.init(timeInterval:0, sinceDate:d)
    }
}

The Wrap Up

So this should get you started using UIDatePicker, there is much more fun to be had that I will go over in the future, but for now it's a date!

I have a post to help you go to the next level and use Calendar Components.