How to display current time on text label?

Use a date formatter to format the date.

var dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .MediumStyle

var timeString = "The time is: \(dateFormatter.stringFromDate(NSDate()))"

Set timeString to your label's text property. Run it on an NSTimer to keep it up to date.


Swift 4:

    var currentDateTime = Date()

    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = .medium

    yourLabel.text = "\(dateFormatter.string(from: currentDateTime))"

Display Live Time/Date in labels.

@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!

var timer = Timer()

override func viewDidLoad() {
    super.viewDidLoad()
    dateLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .long, timeStyle: .none)
    timeLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
}

@objc func tick() {
    dateLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .long, timeStyle: .none)
    timeLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
}

Tags:

Swift