Reputation: 15
I am trying to write a basic timer app that will record the time you hit start and the time you hit end and compare them. All attempts I have made so far have not printed the time, defaulting to its original definition.
let date = Date()
let calendar = Calendar.current
let hourTime = calendar.component(.hour, from: date)
let minutesTime = calendar.component(.minute, from: date)
var TimeWhileGone=0
@IBAction func EndTime(_ sender: Any) {
var button2Alert = UIAlertController(title: "Title", message: "Your Timer have been going for \(minutesTime-TimeWhileGone) minutes!", preferredStyle: UIAlertControllerStyle.alert)
self.present(button2Alert, animated: true, completion: nil)*/
}
@IBAction func startTime(_ sender: Any) {
TimeWhileGone=minutesTime
}
Upvotes: 0
Views: 2057
Reputation: 347194
You need two things, you need two points in time from which to compare, a startTime
and a endTime
(I know sounds simple, but you seem to have missed those points).
You seem to be recording "static" points in time which never change
So when startTime
is called, you initialise the startTime
property to "now" (ie Date()
).
var startTime: Date?
//...
startTime = Date()
When endTime
is called, you mark it and calculate the time difference, using Date().timeIntervalSince
, which gives you a TimeInterval
guard let startTime = startTime else {
return
}
let duration = Date().timeIntervalSince(startTime)
While it might be tempting to use simple modular maths to calculate the format, I'd avoid it, it becomes error prone the larger the interval becomes.
Instead, I'd make use DateComponentsFormatter
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.allowedUnits = [ .day, .hour, .minute, .second]
let durationFormat = formatter.string(from: duration)
For more information, have a look at Formatting a Duration with NSDateComponentsFormatter - while it's a little out of date, it can provide some insights into how the API works
Because these things can be a little complicated, I tend to like to use Playground to test some basic ideas, so the following...
let startTime = Date()
Thread.sleep(forTimeInterval: 2.0)
let duration = Date().timeIntervalSince(startTime)
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.allowedUnits = [ .day, .hour, .minute, .second]
formatter.string(from: duration)
Will eventually display 2s
(I know, thrilling, but it provides the seeds of the idea ;))
Upvotes: 1