×

NSDate and NSDateFormat in Swift


In this tutorial, we created a simple DatePicker which shows date on a label when its valueChanged Event occurs.

NSDate is a class which almost every developer needs to display dates in iOS Apps. Most common operations used are as follows :-

  • Compare Dates
  • Calculate difference between dates
  • Display Dates in using NSDateFormat

Output would be like this


Swift program

// ViewController.swift
//  DateDemoSwift
//  Created by Manish Methani on 21/05/18.
//  Copyright © 2018 Codzify. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    var datePicker : UIDatePicker!
    var button: UIButton!
    var labelDate: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        button = UIButton()
        self.view.addSubview(button)
        button.frame = CGRect(x:self.view.frame.size.width / 2.0 - 100 , y:80, width: 200 , height: 44)
        button.setTitle("Show Date Picker", for: UIControlState.normal)
        button.titleLabel?.textColor = UIColor.white
        button.backgroundColor = UIColor.init(red: 0/255.0, green: 152/255.0, blue: 152/255.0, alpha: 1.0)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 18.0, weight: UIFont.Weight(rawValue: 1.0))
        button.layer.cornerRadius = 2.0
        button.addTarget(self, action: #selector(self.datePickerClicked), for: UIControlEvents.touchUpInside)
        
        
        labelDate = UILabel(frame:CGRect(x:12 , y:80+52 , width: self.view.frame.size.width - 12*2 , height: 40) )
        self.view.addSubview(labelDate)
        labelDate.textColor = UIColor.black
        labelDate.text = "Display Date"
        labelDate.font = UIFont(name: "HelveticaNeue-Thin", size: 16.0)!
        labelDate.textAlignment = NSTextAlignment.center
        labelDate.numberOfLines = 0;
        labelDate.lineBreakMode = NSLineBreakMode.byWordWrapping
        
        
        datePicker = UIDatePicker(frame:CGRect(x: 0, y: self.view.frame.size.height-180 , width: self.view.frame.size.width, height: 200))
        self.view.addSubview(datePicker)
        datePicker.datePickerMode = UIDatePickerMode.dateAndTime
        datePicker.isHidden = true
        button.isSelected = false
        datePicker.addTarget(self, action: #selector(self.dateSelected), for: UIControlEvents.valueChanged)
    }
    
 //Actions
    @objc func dateSelected()
    {
        let dateformatter1 = DateFormatter()
        dateformatter1.dateFormat = "ccc, d MMM yyy"
        
        let dateString1 = dateformatter1.string(from: datePicker.date)
        print("Date Selected \(dateString1)")
        labelDate.text = dateString1
        
        let dateformatter2 = DateFormatter()
        dateformatter2.dateFormat = "dd-MM-yyyy"
        let dateString2 = dateformatter2.string(from: datePicker.date)
        print("Date Selected \(dateString2)")
        
        
        let dateformatter3 = DateFormatter()
        dateformatter3.dateFormat = "dd/MM/yyyy"
        let dateString3 = dateformatter3.string(from: datePicker.date)
        print("Date Selected \(dateString3)")
        
        let dateformatter4 = DateFormatter()
        dateformatter4.dateFormat = "dd MMMM yyyy hh:mm a"
        let dateString4 = dateformatter4.string(from: datePicker.date)
        print("Date Selected \(dateString4)")
        
    }
    
    @objc func datePickerClicked()
    {
        if(button.isSelected == true)
        {
            datePicker.isHidden = true;
            button.isSelected = false
        }
        else
        {
            datePicker.isHidden = false
            button.isSelected = true
        }
    }
    
    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }    
}

Code itself is self-explanatory. We created one button with title Show Date Picker, one label with Text Show date label and one date Picker which fires up .touchUpInside event is triggered. Inside datePickerClicked function which occurs when datePicker's valueChanged event gets tiggered contains various date Formats.

How to convert string into Date ?

Following example illustrates how to convert a string into date

let sampleDate = "2018-04-14T10:44:00+0000"
        
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: sampleDate)!
        
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = NSTimeZone.local
let timeStamp = dateFormatter.string(from: date)
        
print("Date \(timeStamp))")