Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format timer label to hours:minutes:seconds in Swift

Tags:

ios

swift

nstimer

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.

like image 954
Juma Orido Avatar asked Feb 05 '16 03:02

Juma Orido


People also ask

How do I use the timer class in Swift?

The Timer class was created to make it easy to trigger actions, (like updating labels or firing methods), at specific moments in time. Create a new “Single View Application,” give it a name, and set the language to Swift. Make a new view controller in Storyboard, or use the pre-existing default view controller. Add a label.

How to pause and resume a swift timer?

To add the Pause and Resume functionality we will need to add implementation to the pauseButtonTapped method. Swift’s Timer class has a method called invalidate (). It will stop the timer, but not reset the current value of seconds. This will be useful for resuming.

What format is the timer output stored in?

When you’re using a timer control, the timer output is stored in milliseconds like you see here: It probably isn’t ideal to have that value stored in this format. Typically you would want to see this in Hours, Minutes and Seconds format.

How to calculate hours in Excel using timers?

First, you need to get the number of seconds in the timer which you can do using the RoundUp function and passing in the Timers value. You will take that calculation to then get the minutes and you’ll take the minutes to get the hours.


2 Answers

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) 
like image 173
rmaddy Avatar answered Sep 23 '22 17:09

rmaddy


@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.0  let formatter = DateComponentsFormatter() formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale formatter.allowedUnits = [ .hour, .minute, .second ] // Units to display in the formatted string formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale  let formattedDuration = formatter.string(from: duration)  
like image 43
Mark Suman Avatar answered Sep 24 '22 17:09

Mark Suman