type conversion NSDate String

I am trying to display a value of type NSDate with a label.


label.text = date


I get an error saying, "Cannot assign value of type 'NSDate?' to type 'String?'".


I have tried using the "as" operator, but it won't work.


label.text = date as String


I get an error saying, "Cannot convert value of type 'NSDate?' to type 'String?' in coercion"


What is the solution to this problem?

A date isn't a string. You can obtain a string representation of the date by using a formatter (adjust the formatter styles as needed). This will also do the right thing in all regions of the world:


#if swift(>=3)

let theFormatter = DateFormatter()
theFormatter.dateStyle = .mediumStyle
let theString = theFormatter.string(from: Date())

#else

let theFormatter = NSDateFormatter()
theFormatter.dateStyle = .MediumStyle
let theString = theFormatter.stringFromDate(NSDate())

#endif
type conversion NSDate String
 
 
Q