0

I have a date from which I am calculating the elapsed time, like this:

let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.hour, .minute, .second]
dateComponentsFormatter.unitsStyle = .positional
dateComponentsFormatter.zeroFormattingBehavior = .pad
if let timeElapsed = dateComponentsFormatter.string(from: startTime, to: Date()) {
    timerLabel.text = timeElapsed
}

If five seconds has passed it pads all the zeros to make the string say 0:00:05. However, I'm looking to make it say 0:05 for five seconds, 10:05 for 10 minutes and 5 seconds, and 1:10:05 for 1 hour, 10 minutes, and five seconds. How can I do that?

Tometoyou
  • 7,792
  • 12
  • 62
  • 108

1 Answers1

0

You can count number of character is less than or equal 2 then append ahead of timeElapsed like this => "0:" + timeElapsed

var totalTime = ""
let startTime = Date().addingTimeInterval(-50)
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.hour, .minute, .second]
dateComponentsFormatter.unitsStyle = .positional
dateComponentsFormatter.zeroFormattingBehavior = .dropLeading
if let timeElapsed = dateComponentsFormatter.string(from: startTime, to: Date()) {
    if timeElapsed.count <= 2 {
        totalTime = "0:" + timeElapsed
    }else {
        totalTime = timeElapsed
    }
    print(totalTime)
}

Output

0:50
iParesh
  • 2,338
  • 1
  • 18
  • 30