0

There is a NSTimer object in my app that counts elapsed time in seconds.

I want to format an UILabel in my app's interface in the such way it matches the well know standard.

Example

00:01 - one second

01:00 - 60 seconds

01:50:50 - 6650 seconds

I wonder how to do that, do you know any pods/libraries that creates such String based on Int number of seconds?

Obviously I can come with a complicated method myself, but since it's recommended to not reinvent the wheel, I'd prefer to use some ready-to-use solution.

I haven't found anything relevant in Foundation library, nor in HealthKit

Do you have any suggestions how to get it done? If you say "go and write it yourself" - that's ok. But I wanted to be sure I'm not missing any simple, straightforward solution.

thanks in advance

theDC
  • 6,364
  • 10
  • 56
  • 98
  • @EricAya Thanks! Could you provide an example of usage in my case? Strongly appreciated – theDC Sep 30 '16 at 10:27

2 Answers2

7

(NS)DateComponentsFormatter can do that:

func timeStringFor(seconds : Int) -> String
{
  let formatter = DateComponentsFormatter()
  formatter.allowedUnits = [.second, .minute, .hour]
  formatter.zeroFormattingBehavior = .pad
  let output = formatter.string(from: TimeInterval(seconds))!
  return seconds < 3600 ? output.substring(from: output.range(of: ":")!.upperBound) : output
}

print(timeStringFor(seconds:1)) // 00:01
print(timeStringFor(seconds:60)) // 01:00
print(timeStringFor(seconds:6650)) // 1:50:50
vadian
  • 274,689
  • 30
  • 353
  • 361
0

Figured it out based on this answer, quite simple!

func createTimeString(seconds: Int)->String
{
    var h:Int = seconds / 3600
    var m:Int = (seconds/60) % 60
    var s:Int = seconds % 60
    let a = String(format: "%u:%02u:%02u", h,m,s)
    return a

}
Community
  • 1
  • 1
theDC
  • 6,364
  • 10
  • 56
  • 98