Format timer label to hours:minutes:seconds in Swift Format timer label to hours:minutes:seconds in Swift ios ios

Format timer label to hours:minutes:seconds in Swift


Your calculations are all wrong.

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


@rmaddy's solution is accurate and answers the question. However, neither the question nor the solution take into account international users. I suggest using DateComponentsFormatter and let the framework handle the calculations and formatting. Doing so makes your code less error prone and more future proof.

I came across this blog post that provides a concise solution:http://crunchybagel.com/formatting-a-duration-with-nsdatecomponentsformatter/

Pulled from that post, this is the code snippet that would replace the code you're currently using to make your calculations. Updated for Swift 3:

let duration: TimeInterval = 7200.0let formatter = DateComponentsFormatter()formatter.unitsStyle = .positional // Use the appropriate positioning for the current localeformatter.allowedUnits = [ .hour, .minute, .second ] // Units to display in the formatted stringformatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the localelet formattedDuration = formatter.string(from: duration) 


Swift5

var totalSecond = Int()var timer:Timer?

call startTimer() based on requirement-

func startTimer(){timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countdown), userInfo: nil, repeats: true)}@objc func countdown() {    var hours: Int    var minutes: Int    var seconds: Int    if totalSecond == 0 {        timer?.invalidate()    }    totalSecond = totalSecond - 1    hours = totalSecond / 3600    minutes = (totalSecond % 3600) / 60    seconds = (totalSecond % 3600) % 60    timeLabel.text = String(format: "%02d:%02d:%02d", hours, minutes, seconds)}

Done