DCDC DCDC - 27 days ago 6
iOS Question

Swift: Formatting time string based on number of seconds

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.


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


(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