user3766930 user3766930 - 6 months ago 19
Swift Question

How can I convert a date format to another date format in Swift?

I currently have a code:

let now = NSDate()
let result: NSDate
result = Cal.iso8601.dateByAddingUnit(.Year, value: -5, toDate: now, options: [])!
return Cal.iso8601.startOfDayForDate(result)

that generates a date in the format:

2016-09-15 22:00:00 +0000

and I want to convert it to this date format:


how can I do it in Swift?


DateFormatter requires a lot of resources so use this extension so that you only create one instance of the formatter.

struct Formatter {
    static let instance = NSDateFormatter(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
extension NSDateFormatter {
    convenience init(dateFormat: String) {
        self.dateFormat = dateFormat

Then just call it with:

// dateTime = the date that you want to format
let date = Formatter.instance.dateFromString(dateTime)