I use DateComponentsFormatter
to format TimeInterval
in iOS. If I have a result of 1:09 a leading zero should be shown. That the result looks like this: 01:09. Is this possible with DateComponentsFormatter
.
Here is my example code:
let interval: TimeInterval = 4155
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.hour, .minute]
formatter.zeroFormattingBehavior = .pad
formatter.collapsesLargestUnit = false
formatter.string(from: interval)
use zeroFormattingBehavior = .pad
for example:
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.unitsStyle = .positional
formatter.zeroFormattingBehavior = .pad
let outPut = formatter.string(from: TimeInterval(duration)) ?? ""
If you want to format the interval as time, then the best solution is to use DateFormatter
:
let interval: TimeInterval = 4155
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "HH:mm"
print(formatter.string(from: Date(timeIntervalSinceReferenceDate: interval)))
That will always use the same format, always displaying hours.
The DateComponentFormatter
does not pad with zeros because it is supposed to be used with higher units, e.g. you could get results like "300:24" if your TimeInterval
is high enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With