UIDatePicker example in Swift

In these two videos we will learn how to create UIDatePicker, read date selected by user and display selected date in different user friendly formats. We will also learn how to convert NSDate to milliseconds and back.

Create UIDatePicker

Convert NSDate into milliseconds and back

Source code:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var myDatePicker: UIDatePicker!
    @IBOutlet weak var label_1: UILabel!
    @IBOutlet weak var label_2: UILabel!
    @IBOutlet weak var label_3: UILabel!
    @IBOutlet weak var label_4: UILabel!

    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.

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

    @IBAction func displayButtonTapped(sender: AnyObject) {
        let formatter = NSDateFormatter()
        let myLocale = NSLocale(localeIdentifier: "en_CA")
        formatter.locale = myLocale
        label_1.text =  NSDateFormatter.localizedStringFromDate(myDatePicker.date, dateStyle: NSDateFormatterStyle.FullStyle, timeStyle: NSDateFormatterStyle.ShortStyle)
        formatter.dateFormat = "MMMM dd, YYYY"
        label_2.text = formatter.stringFromDate(myDatePicker.date)
        formatter.dateFormat = "MMM dd, YYYY"
        label_3.text = formatter.stringFromDate(myDatePicker.date)
        formatter.dateFormat = "EEEE, YYYY/mm/dd"
        label_4.text = formatter.stringFromDate(myDatePicker.date)

        // Getting milliseconds from Date
        let seconds = myDatePicker.date.timeIntervalSince1970
        let milliseconds = seconds * 1000
        // Save this value in database
        // Creating Date from milliseconds
        let newDate = NSDate(timeIntervalSince1970: milliseconds/1000)
        print(NSDateFormatter.localizedStringFromDate(newDate, dateStyle: NSDateFormatterStyle.FullStyle, timeStyle: NSDateFormatterStyle.ShortStyle))