AlexanderHart AlexanderHart - 4 months ago 25
Swift Question

NSDate Formatter Bug

I have a Unix timestamp that I am attempting to convert with

NSDateFormatter()
, but when I try to pass my
NSDate
variable, I get an error:
Cannot assign value of type 'String' to type 'NSDate?'


var releaseDate: NSDate?

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)

let seconds = Double(self.userA.releaseDate)

let timestampDate = NSDate(timeIntervalSince1970: seconds)

let stringTimeStamp = timestampDate.description

print(stringTimeStamp) // 2016-07-29 04:49:54 +0000

let releaseDateFormatter = NSDateFormatter()
releaseDateFormatter.dateFormat = "hh:mm:ss a"
releaseDate = releaseDateFormatter.stringFromDate(timestampDate)
}


I'm confused because didn't I explicity declare
timestampDate
as
NSDate
?

Answer

The problem is not the timestampDate. The problem is that releaseDate is a NSDate? and you are trying to put the result of stringFromDate to it, which returns a String.

If you want to convert the timestamp to a user-readable string, you probably want to declare releaseDate as String.