Timer Issue / explanation

I am trying to update the label with the current Time.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    let date = Date()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }
    
    
    func updateTime(){
        
        label.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .long)
        
    }
    

}

when I am using at updateTime() label.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .long) I am getting the result that I want

When I am using label.text = DateFormatter.localizedString(from: date, dateStyle: .none, timeStyle: .long)

the timer is not working. can someone please explain me ? ?

From my understanding I if I use a date and not Date() then I need a timer to count and calculate. If so any suggestions ?

Hi @scy

What do you mean by “timer is not working”? Your updateTime() function will trigger no matter what you put in your DateFormatter.localizedString parameters. Do you have a crash or error or something else?

Nikita

Hi @nikita_gaydukov

When I use Date() in DateFormatter.localizedString(from Date(), . . . . .) it works and it prints every second the value from Date()

But when you pass the constant let date = Date() meaning DateFormatter.localizedString(from: date , …) then it is just updating the same constant since it is not updating.

My question if I can make it completely clear is **How I can make a constant type Date like let date = Date() make it start showing a count up from the time that is getting the let date = Date() and then count up in a label?

example : assume that date = 2017-08-07 04:00:00 as Date

how I can make this constant showing in a label a count up like
2017-08-07 04:01:00
2017-08-07 04:02:00
2017-08-07 04:03:00

or even seconds

Thanks a lot !!

Hi @scy

In general the Timer class is not accurate for this sort of things, so you cannot rely on just incrementing date (because your updateTime func woudn’t be called every ~1 second, but not exactly every 1 second).
If i understood your question correctly, you will need to store the date when your timer actually started, then on every timer tick check the difference between the timer start date and a current date, then add that difference to your your date constant. This way you will have the accurate timer.

Nikita

Hi Nikita and thanks fro your Answer again. Yes that was the question and you are right.

Thumbs up !

This topic was automatically closed after 166 days. New replies are no longer allowed.