Cannot assign value of type "NSDate" to value of type "String?"

I taught myself quickly, and I'm still very new, but I decided to create a simple program that prints the current time when you press the button. The code from the viewcontroller file is as follows:

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    @IBOutlet weak var LblTime: UILabel!
    @IBAction func BtnCalltime(sender: AnyObject) {
            var time = NSDate()
            var formatter = NSDateFormatter()
            formatter.dateFormat = "dd-MM"
            var formatteddate = formatter.stringFromDate(time)
            LblTime.text = time
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

I have a problem with the line:

LblTime.text = time

I keep getting the error:

Cannot assign value of type "NSDate" to value of type "String?"

I tried using:

lblTime.text = time as! string?

and

lblTime.text = time as! string

but it still does not work, I would be very grateful for any help. Thanks

+4
source share
3 answers

You need to use the value from formatting.

@IBAction func BtnCalltime(sender: AnyObject) {
    var time = NSDate()
    var formatter = NSDateFormatter()
    formatter.dateFormat = "dd-MM"
    var formatteddate = formatter.stringFromDate(time)
    LblTime.text = formatteddate
}
+6
source

You have already created a string from NSDate, but just do not use it.

lblTime.text = formatteddate
+3

Date is now preferred over NSDate. This is an overlay class, meaning that both will work, but Date but has many advantages, this answer lists some of them.

Here's how to format a date into a string using Date instead of NSDate.

var time = Date()
var formatter = DateFormatter()
formatter.dateFormat = "MMM d yyyy, h:mm:ss a"
let formattedDateInString = formatter.string(from: time)

dateLabel.text = formattedDateInString

A great site for getting formatting strings is http://nsdateformatter.com/ I had no idea what "MMM d yyyy, h:mm:ss a"would be the same Mar 1, 7:02:35 AM, but the site would simplify it.

0
source

All Articles