AlexanderHart AlexanderHart -5 years ago 194
Swift Question

NSDate Formatter Bug

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

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

var releaseDate: NSDate?

override func viewDidAppear(animated: Bool) {

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download