1

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!

Ryan Cocuzzo
  • 3,109
  • 7
  • 35
  • 64

3 Answers3

3

You really want to go from a NSDate to a String, so use stringFromDate:

let convertedDate = formatter.stringFromDate(currentDate)
Andrew
  • 15,357
  • 6
  • 66
  • 101
1

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

Jeet
  • 5,569
  • 8
  • 43
  • 75
0

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"
Community
  • 1
  • 1
Edison
  • 11,881
  • 5
  • 42
  • 50