DateComponentsFormatter doesn't format fractional units

I would like to format TimeInterval values, but DateComponentsFormatter doesn't seem to respect `allowsFractionalUnits`.


let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.hour]
formatter.allowsFractionalUnits = true
let durations:[TimeInterval] = [1800.0, 3600.0, 5400.0, 7200.0, 10000.0]
durations.forEach{ print("\($0) -> \(formatter.string(from: $0)!)") }


This code produces the following output:


1800.0 -> 0 hours

3600.0 -> 1 hour

5400.0 -> 1 hour

7200.0 -> 2 hours

10000.0 -> 2 hours


I was expecting it to print something like:


1800.0 -> 0.5 hours

3600.0 -> 1 hour

5400.0 -> 1.5 hours

7200.0 -> 2 hours

10000.0 -> 2.8 hours


Am I doing something wrong?

Replies

I agree that your usage is reasonable based on the documentation. However, looking at how

allowsFractionalUnits
is implemented I can’t see any way that this could possibly work. I recommend you file a bug about this; either DateComponentsFormatter is broken or the documentation needs to be clarified. Please posting your bug number, just for the record.

Beyond that, if you’d like some to take a more in-depth look into whether it’s possible to do this, I recommend you open a DTS tech support incident.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"