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
dateFormat = "yyyy-MM-dd'T'HH:mm:ss.
Get current time in “YYYY-MM–DD HH:MM:SS +TIMEZONE” format in Swift. This is the easiest way to show the current date-time.
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)
}
}
Extension for getting string against date formats
extension Date {
func toString(format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
Date().toString(format:"H:mm")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With