Search code examples
iosswiftdatensdateformatter

DateComponentsFormatter show leading zero


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)

Solution

  • 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.