I need to create a simple stopwatch in Swift using the method timeIntervalSince(). I don't really understand how to use timeIntervalSince (what I need and how to implement it) and how to transform it into a String that will show me the passed time like "00:00:00".
I know I need to use a Timer to update the Label and invalidate it when clicking on "Stop".
I'd really appreciate any help on this. Let me know if you need more information.
The method timeIntervalSince(_:)
is a method of Date
. It gives you the number of seconds that have passes since some other date and the date you are asking.
So,
Create a StopwatchVC.
Give StopwatchVC a startTime
var of type Date.
Also give it a Timer
var. Lets call that updateTimer
.
When the user taps the start button, save Date()
(the time right now) into startTime. Also start a repeating timer, updateTimer
that fires every 1/10 second. (or however often you want to update your stopwatch, but note that faster than 1/60 is pointless because the screen can't update any faster than that, and timers are only accurate to about 1/50 sec anyway.)
Each time updateTimer
fires, calculate the number of seconds that have elapsed since the start time and display it to the screen:
let seconds = Date().timeIntervalSince(startTime)
Date()
is the current date and time, with sub-millisecond accuracy.
Date().timeIntervalSince(startTime)
will give you the number of seconds since startTime
, again with sub-millisecond accuracy.
Format and display the elapsed time to the screen. You could use a DateComponentsFormatter
or build a time string yourself using a NumberFormatter, or even String(format:)