Search code examples
iosobjective-cnsdatecomponentsformatter

NSDateComponentsFormatter Units Separator


I want to convert time in minutes to user friendly string. Following code resolves the issue, except one thing - I want result to look like 1 hr 30 min, however I got 1 hr, 30 min. How to specify units separator for NSDateComponentsFormatter? Of course, I can remove all commas manually, but it isn't looks like the best way for me.

    NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
    formatter.allowedUnits = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
    formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleShort;

    NSLog(@"%@", [formatter stringFromTimeInterval:90*60]);

Solution

  • If your application is targeting OS X 10.12 (or later, I presume) or iOS 10.10 (or later), then Apple added a new units style called "NSDateComponentsFormatterUnitsStyleBrief"

    formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleBrief
    

    and it will print out "1 hr 30 min"

    https://developer.apple.com/reference/foundation/nsdatecomponentsformatterunitsstyle/nsdatecomponentsformatterunitsstylebrief?language=objc