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/counter to count and calculate. If so any suggestions ?
Thanks a lot
P
In your second example, date
is a constant value. So even though updateTime() is called every second, it is setting the label to the same value every time.
From the comments, it seems you want to be able to advance a constant time when the timer is running.
To count up from an arbitrary constant
Date
, store a start
time when the timer is started. Use that to compute the interval
the timer has been running, and then use that interval
to advance date
:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
let date = Date()
var start: Date?
override func viewDidLoad() {
super.viewDidLoad()
// Save the time when the timer starts
start = Date()
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
func updateTime(){
// compute how long the timer has been running
let interval = Date().timeIntervalSince(start!)
// compute new date based on how long the timer has been running
let newDate = date.addingTimeInterval(interval)
label.text = DateFormatter.localizedString(from: newDate, dateStyle: .none, timeStyle: .long)
}
}
The timer firing is not very accurate, and you might see your counting pause for a second and then jump 2 seconds. If you make your timer interval something smaller, like 0.1
for instance, you can avoid a visual glitch.