5

I am teaching myself swift and I am still very new but I decided to make a simple app that prints the current time when you press a 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 am having an issue with the line:

LblTime.text = time

I keep getting the error:

Cannot assign a value of type 'NSDate' to a value of type 'String?'

I have tried using:

lblTime.text = time as! string?

And:

lblTime.text = time as! string

but it does still not work, I would be very appreciative of some help. Thanks

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
MrGuy797
  • 55
  • 1
  • 1
  • 7
  • http://stackoverflow.com/questions/6288371/how-to-convert-string-to-nsdate-in-iphone this will help you – wm.p1us Jul 14 '15 at 20:58

3 Answers3

8

You need use a value from formatter.

@IBAction func BtnCalltime(sender: AnyObject) {
    var time = NSDate()
    var formatter = NSDateFormatter()
    formatter.dateFormat = "dd-MM"
    var formatteddate = formatter.stringFromDate(time)
    LblTime.text = formatteddate
}
Tomáš Linhart
  • 13,509
  • 5
  • 51
  • 54
3

You made the string from an NSDate already, you just aren't using it.

lblTime.text = formatteddate
Dare
  • 2,497
  • 1
  • 12
  • 20
0

Date is now preferred over NSDate. It is an overlay class meaning both will work, but Date but has a lot of advantages, this answer lists some of those.

Here is how to format a date to 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 to get the formatter strings is http://nsdateformatter.com/ I had no idea that "MMM d yyyy, h:mm:ss a" would equal Mar 1, 7:02:35 AM but the site makes it easy.

Joshua Dance
  • 8,847
  • 4
  • 67
  • 72