Convert Date To String & Vice-Versa Swift 4 - iOS - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

11 Oct 2017

Convert Date To String & Vice-Versa Swift 4 - iOS

Convert Date To String & Vice-Versa Swift 4 - iOS

Date To String:


For converting Date to String we are going to create extension for Date as follow:
extension Date
{
    func toString( dateFormat format  : String ) -> String
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
}

In above method we can set the required output date format.

Usage:

Add the following lines of code for usage:

let dateString = Date().toString(dateFormat: "yyyy/MMM/dd HH:mm:ss")
print("dateString is \(dateString)")

// output will be 'dateString is 2017/Oct/11 17:16:23'

String To Date:


For converting string to date, we have to give the date format as the string.

Add the following extension to String:
extension String
{
    func toDate( dateFormat format  : String) -> Date
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
        return dateFormatter.date(from: self)!
    }
    
}

Usage:

Add the following lines of code for usage:
let dateString = "2017-10-10 15:56:25"
let date = dateString.toDate(dateFormat: "yyyy-MM-dd HH:mm:ss")
print("Date is \(date)")

// output is 'Date is 2017-10-10 15:56:25 +0000'

1 comment:

Post Top Ad