Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 977
patrickS Avatar asked Apr 24 '18 14:04

patrickS


2 Answers

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)) ?? ""
like image 161
Alvin John Avatar answered Sep 24 '22 01:09

Alvin John


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.

like image 33
Sulthan Avatar answered Sep 24 '22 01:09

Sulthan