You have to declare 2 different NSDateFormatters
, the first to convert the string to a NSDate
and the second to print the date in your format.
Try this code:
let dateFormatterGet = NSDateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss" let dateFormatterPrint = NSDateFormatter() dateFormatterPrint.dateFormat = "MMM dd,yyyy" let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26") print(dateFormatterPrint.stringFromDate(date!))
Swift 3 and higher:
From Swift 3 NSDate
class has been changed to Date
and NSDateFormatter
to DateFormatter
.
let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss" let dateFormatterPrint = DateFormatter() dateFormatterPrint.dateFormat = "MMM dd,yyyy" if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") { print(dateFormatterPrint.string(from: date)) } else { print("There was an error decoding the string") }