Search code examples
iosswiftnsdateformatter

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:

2016-09-16T13:49:23.221Z

how can I do it in Swift?


Solution

  • 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.init()
            self.dateFormat = dateFormat
        }
    }
    

    Then just call it with:

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