Date formatting not working in Swift 3

ICL1901 picture ICL1901 · Jul 25, 2016 · Viewed 26.7k times · Source

I'm having a problem with NSDate in a function. Essentially, the formatting is not working, and I need another set of eyes to see what I'm doing wrong.

Code:

 @IBOutlet weak var dateField: NSTextField!

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd yyyy"
let currentDate = NSDate()

convertedDateString = dateFormatter.string(from:currentDate as Date)
dateField.stringValue = convertedDateString as String

print("convertedDate: ", convertedDateString)
print("dateField.stringValue: ", dateField.stringValue)

Result:

convertedDate: July 25 2016
dateField.stringValue: 7/25/16

Answer

SaRaVaNaN DM picture SaRaVaNaN DM · Nov 7, 2016
Date().toString() // convert date to string with userdefined format.

extension Date {
        func toString() -> String {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "MMMM dd yyyy"
            return dateFormatter.string(from: self)
        }
    }