Recusiwe Recusiwe - 1 month ago 14
iOS Question

Date in Swift 3 conversion

I want this date "2016-10-18 22:06:20 +0000" to "18-10-2016", is this possible? I managed to get the date as follows:

var formatter = DateFormatter()
formatter.dateFormat = "yyy-MM-dd'HH:mm:ss.SSSZ"
let stringDate = formatter.string(from: currentDate)


The above gives me "10/18/16", but how can I get "18-10-2016"?

Answer

Solution in Swift 3

extension Foundation.Date {

func dashedStringFromDate() -> String {
    let dateFormatter = DateFormatter()
    let date = self
    dateFormatter.dateFormat = "dd-MM-yyyy"
    return dateFormatter.string(from: date)
  }
}

Example

let date = Foundation.Date()
let formatedDate = date.dashedStringFromDate()
Comments