As Rob said, you must be careful with performance creating DateFormatters, use the tips from that WWDC session.
I am doing this as extensions of NSDate and NSDateFormatter (code tested in Swift 2, 3 and 4):
extension NSDate {
func PR2DateFormatterUTC() -> String {
return NSDateFormatter.PR2DateFormatterUTC.stringFromDate(self)
}
//... more formats
}
extension NSDateFormatter {
fileprivate static let PR2DateFormatterUTC: NSDateFormatter = {
let formatter = NSDateFormatter()
let timeZone = NSTimeZone(name:"UTC")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = timeZone
return formatter
}()
//... more formats
}
Usage:
let dateStringUTC = NSDate().PR2DateFormatterUTC()