4

I have a stopwatch app I'm making that currently shows the minutes, seconds and milliseconds on a UILabel. It has a 'Start' button and a 'Stop' button. The code is below. How do I add hours to it? Also how do I make it continue where it was, when I stopped it? Currently if I press start again, it resets and starts over. I'll add a reset button later.

//Variables
var startTime = NSTimeInterval()

//Start Button
@IBAction func start(sender: AnyObject) {
   let aSelector : Selector = “updateTime”
   timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
   startTime = NSDate.timeIntervalSinceReferenceDate()
}

//Stop Button
@IBAction func stop(sender: AnyObject) {
   timer.invalidate()
}

//Update Time Function
func updateTime() {

   var currentTime = NSDate.timeIntervalSinceReferenceDate()

   //Find the difference between current time and start time.

   var elapsedTime: NSTimeInterval = currentTime - startTime

   //calculate the minutes in elapsed time.

   let minutes = UInt8(elapsedTime / 60.0)

   elapsedTime -= (NSTimeInterval(minutes) * 60)

   //calculate the seconds in elapsed time.

   let seconds = UInt8(elapsedTime)

   elapsedTime -= NSTimeInterval(seconds)

   //find out the fraction of milliseconds to be displayed.

   let fraction = UInt8(elapsedTime * 100)

   //add the leading zero for minutes, seconds and millseconds and store them as string constants

   let strMinutes = String(format: "%02d", minutes)
   let strSeconds = String(format: "%02d", seconds)
   let strFraction = String(format: "%02d", fraction)

   //concatenate minuets, seconds and milliseconds as assign it to the UILabel

   displayTimeLabel.text = “\(strMinutes):\(strSeconds):\(strFraction)”

}
jwvh
  • 50,871
  • 7
  • 38
  • 64
ChallengerGuy
  • 2,385
  • 6
  • 27
  • 43
  • 1
    Please, use [code blocks](http://stackoverflow.com/editing-help#code) for describing your question instead of include screenshots of your code. This make copy & paste possible, among other things.You can also configure the [highlighting of your code](http://stackoverflow.com/editing-help#syntax-highlighting). – Álvaro Arranz Apr 23 '15 at 19:27
  • Ok, sorry and thank you! – ChallengerGuy May 05 '15 at 15:21

2 Answers2

3

You can calculate hours so

elapsedtime / 3600

Read there more NSTimeInterval to HH:mm:ss?

Community
  • 1
  • 1
cmashinho
  • 605
  • 5
  • 21
0

To make continues to count on the stopwatch:

Create var stopTime : NSTimeInterval = 0

When stop() function is called, insert this code:

 stopTime = elapsedTime

In start() function, replace to:

elapsedTime = (currentTime - startTime) + stopTime

Or You can use NSDate(), NSDateFormatter() to solve this problem. Reference here enter link description here