DateComponentsFormatter needs rouding behavior

Number:rdar://37971185 Date Originated:27-Feb-2018 10:34 PM
Status:Open Resolved:
Product:iOS + SDK Product Version:Latest
Classification:UI/Usability Reproducible:Not Applicable
DateComponentsFormatter currently gives developers no way to specify how to handle rounding. For example, if I want to display 2 hours and 55 minutes only in terms of hours (`allowedUnits = [.hour]`), the formatter prints 2.

I think most people would agree that 3 is closer to reality, so it would be nice to be able to tell DateComponentsFormatter what rounding behavior is desired.

Steps to Reproduce:
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.day]
formatter.unitsStyle = .full

print(formatter.string(from: 345_000))) // almost 6 days

Expected Results:
I can specify whether the snippet above prints "5" or "6"

Actual Results:
The output is always "5"




A possible solution is to round the number beforehand. For example, if you are using a TimeInterval, you could call .rounded() on the time interval.

let formatter = DateComponentsFormatter()

formatter.allowedUnits = [.minute, .second]

formatter.zeroFormattingBehavior = .pad

let durationString = formatter.string(from: asset.duration.rounded())

There are other rounding options such as:



By creativerunway at Jan. 9, 2019, 5:22 p.m. (reply...)

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!