Reputation: 7778
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
Upvotes: 17
Views: 26944
Reputation: 2668
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")
Upvotes: 8
Reputation: 9
The issue i had was not deleting the App from my phone before re installing and testing. The code was working in the simulator but not the phone. Hope this helps
Upvotes: 0
Reputation: 4410
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)
}
}
Upvotes: 32
Reputation: 5757
This is what i try on the playground and it works.
import Foundation
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM dd yyyy"
let currentDate = NSDate()
let convertedDateString = dateFormatter.stringFromDate(currentDate)
var dateField:NSTextField = NSTextField()
dateField.stringValue = convertedDateString as String
print(convertedDateString) //July 25 2016
print(dateField.stringValue) //July 25 2016
The only different was that i change to NSDateFormatter
and instead of dateFormatter.string
i have dateFormatter.stringFromDate
.
Did you accidentally set some value in the storyboard or xib that you have the NSTextField
?
Upvotes: 5