Format timer label to hours:minutes:seconds in Swift

mjoe7 picture mjoe7 · Feb 5, 2016 · Viewed 33.1k times · Source

I have an NSTimer which counts DOWN from 2 hours until 0.

Here are some of my code:

var timer = NSTimer()
let timeInterval:NSTimeInterval = 0.5
let timerEnd:NSTimeInterval = 0.0
var timeCount:NSTimeInterval = 7200.0 // seconds or 2 hours

// TimeString Function

func timeString(time:NSTimeInterval) -> String {
    let minutes = Int(time) / 60
    let seconds = time - Double(minutes) * 60
    let secondsFraction = seconds - Double(Int(seconds))
    return String(format:"%02i:%02i.%01i",minutes,Int(seconds),Int(secondsFraction * 10.0))
}

The Timer Label is:

TimerLabel.text = "Time: \(timeString(timeCount))"

HOWEVER, my timer label shows as:

Time: 200:59.0

How do I format my timer label to look like this:

Time: 01:59:59 // (which is hours:minutes:seconds)?

[Please note that I have no problems with my countdown timer, I only need to know how to CHANGE THE TIME FORMAT using the TimeString function.]

EDIT: Someone mentioned that my question is a possible duplicate of this one: Swift - iOS - Dates and times in different format. HOWEVER, I am asking on how do I change the time format using the TimeString function that I gave above. I am not asking for another WAY on how to do it.

For instance:

let minutes = Int(time) / 60

gives me "200" minutes. etc.

Answer

rmaddy picture rmaddy · Feb 5, 2016

Your calculations are all wrong.

let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)