Reputation: 3219
I have been looking into retrieving the date and time in Swift and this is the recommended strategy for getting a short, readable Date/Time output:
let currentDate = NSDate()
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .ShortStyle
let convertedDate = formatter.dateFromString(currentDate) //ERROR HERE
print("\n\(convertedDate)")
but this throws an Exception saying that currentDate
is not a valid parameter to be passed because it is of type NSDate
instead of String
Can you help me understand why this is the case? I have only found similar approaches to this when retrieving Date and Time. Thank you very much, all help is appreciated!
Upvotes: 1
Views: 210
Reputation: 5659
Here is exactly how you can do it in swift 3 syntax -
let currentDate = NSDate()
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateStyle = .short
formatter.timeStyle = .short
let convertedDate = formatter.string(from: currentDate as Date)
BR
Upvotes: 1
Reputation: 11987
Leo Dabus wrote a good extension for getting a String from NSDate in this Question by Friso Buurman. Obrigado Leo 🙇🏽👍🏽
Mods please note: I have borrowed from it and re-written it because the original code used the same variable names for the declaration of the static constants
, string variables
and argument parameters
which can be confusing for new coders.
It's a great extension by Leo and it contains mostly NSDateFormatter
boiler-plate code you can find in the Apple docs.
Swift 2
extension NSDateFormatter {
convenience init(stringDateFormat: String) {
self.init()
self.dateFormat = stringDateFormat
}
}
extension NSDate {
struct Formatter {
static let newDateFormat = NSDateFormatter(stringDateFormat: "dd-MM-yyyy")
}
var myNewDate: String {
return Formatter.newDateFormat.stringFromDate(self)
}
}
Console Output:
print(NSDate().myNewDate) // "05-07-2016\n"
Swift 3
extension DateFormatter {
convenience init(stringDateFormat: String) {
self.init()
self.dateFormat = stringDateFormat
}
}
extension Date {
struct Formatter {
static let newDateFormat = DateFormatter(stringDateFormat: "dd-MM-yyyy")
}
var myNewDate: String {
return Formatter.newDateFormat.string(from: self)
}
}
Console Output:
print(Date().myNewDate) // "05-07-2016\n"
Upvotes: 0
Reputation: 15377
You really want to go from a NSDate
to a String
, so use stringFromDate
:
let convertedDate = formatter.stringFromDate(currentDate)
Upvotes: 3