iosswiftnsdatecomponentsformatter

Setting multiple allowedUnits for NSDateComponenstFormatter in Swift


Background:

When formatting an NSTimeInterval using an NSDateComponentsFormatter, it's often handy to use the allowedUnits property to round the resulting string to a relevant time unit.

For example, I may not be interested in getting time to the second, so setting the allowedUnits to minutes gets an appropriately rounded output string:

let duration: NSTimeInterval = 3665.0    // 1 hour, 1 minute and 5 seconds
let durationFormatter = NSDateComponentsFormatter()

durationFormatter.unitsStyle = .Full
durationFormatter.zeroFormattingBehavior = .DropAll
durationFormatter.allowedUnits = .Minute

let formattedDuration = durationFormatter.stringFromTimeInterval(duration)

formattedDuration will be "61 Minutes".

The problem:

How would you go about setting allowedUnits to .Hour and .Minute so the formatted duration would be "1 hour, 1 minute" instead?

The NSDateComponentFormatter Class Reference doesn't really cover how to do this.


Solution

  • As suggested by Leo, you can simply provide the allowedUnits in an array like so:

    durationFormatter.allowedUnits = [.Hour, .Minute]