iosswiftnsdatecomponentsformatter

DateComponentsFormatter - showing only hour described as minutes - bug?


I'm using DateComponentsFormatter to achieve something like that: "1 hour, 30 min". This is my code for that:

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .short
formatter.allowedUnits = [.hour, .minute]
return formatter.string(from: 90)!

This should return 1 hour and 30 minutes but my output is "1 min". Is something wrong with my code or is it iOS bug?


Solution

  • The DataComponentsFormatter string(from: TimeInterval) method that you are using expects the time interval in seconds.

    So you are asking the formatter to format 90 seconds, not 90 minutes.

    This will solve your issue:

    return formatter.string(from: 90 * 60)! // 90 minutes
    

    When ever in doubt about such things, read the documentation. The documentation shows the following for the parameter description:

    The time interval, measured in seconds. The value must be a finite number. Negative numbers are treated as positive numbers when creating the string.