Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get date and time to show a clock in UILabel

Tags:

uilabel

swift

I'm new to swift (and programming in general) and right now I'm working on a project that I'd like to display a clock in a label.

right now I have this in my model:

class CurrentDateAndTime {

let currentTime = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .MediumStyle)
}

and then call it into the label with this code in my view controller:

@IBOutlet weak var currentTimeLabel: UILabel!

let currentTime = CurrentDateAndTime()



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    currentTimeLabel.text = currentTime.currentTime
}

The problem is this doesn't update on a second interval to show the actual time. And eventually I will be needing to get a difference between two time stamps so that I can log hours between a "start time" and a "stop time". Is this even the best/simplest way of doing it? Any clues toward my objective will be much appreciated.

like image 639
Leighton Avatar asked Nov 14 '14 13:11

Leighton


2 Answers

Use NSTimer to schedule the callbacks at your desired interval -- in this case,

  • call tick() on self every second
  • tick() fetches the current time string and updates the UILabel

    class MyViewController {
        @IBOutlet weak var currentTimeLabel: UILabel!
    
        var timer = NSTimer()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view, typically from a nib.
    
            timer = NSTimer.scheduledTimerWithTimeInterval(1.0
                                                                target: self,
                                                              selector: #selector(tick),    
                                                              userInfo: nil, 
                                                               repeats: true)
        }
    
        @objc func tick() {
            currentTimeLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(),
                                                                            dateStyle: .MediumStyle,
                                                                            timeStyle: .MediumStyle)
        }
    }
    

Swift 4.0 update:

class MyViewController : UIViewController {
    @IBOutlet weak var currentTimeLabel: UILabel!

    var timer = Timer()

    override func viewDidLoad() {
        super.viewDidLoad()
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
    }

    @objc func tick() {
        currentTimeLabel.text = DateFormatter.localizedString(from: Date(),
                                                              dateStyle: .medium,
                                                              timeStyle: .medium)
    }
}
like image 153
Bob Mazanec Avatar answered Nov 15 '22 23:11

Bob Mazanec


This is a more current (2016) Swift example:

import Cocoa

class ViewController: NSViewController {
    @IBOutlet weak var labelClock: NSTextField!
    let dateFormatter = DateFormatter()

    override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view.
       dateFormatter.dateStyle = .medium
       dateFormatter.timeStyle = .long
       Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateLabel), userInfo: nil, repeats:true);
    }

    override var representedObject: Any? {
       didSet {
           // Update the view, if already loaded.
       }
    }


    func updateLabel() -> Void {
        labelClock.stringValue = dateFormatter.string(from: Date());
    }
}
like image 35
Thomas Avatar answered Nov 15 '22 23:11

Thomas