8

I want to convert a NSTimeInterval to a format like

1w 3d 4h 15m 21s

How can I achieve this in a locale-friendly way? Is there a cocoa API for doing this, or at least is there a way to get the "w", "d", "h", "m", "s" in the user's locale?

tenfour
  • 36,141
  • 15
  • 83
  • 142
  • Do you mean by locale-friendly that in Spanish the result would be the following: **1s 3d 4h 15m 21s**? Note: (semana = week, dia = day, minuto = minute, Segundo = second) – Black Frog Jan 29 '15 at 16:15
  • yes, exactly. Similar to how `NSDateFormatter` would also use localized formats and language. – tenfour Jan 29 '15 at 16:16
  • You can always construct the string with replacement variables and [use standard "localized string" operations](http://stackoverflow.com/a/14984616/581994) to translate as needed. – Hot Licks Jan 29 '15 at 16:54

1 Answers1

12

NSDateComponentsFormatter is what you want. It may not produce exactly what you're looking for, but my impression is that it aims to produce output that conforms to ICU standard conventions. For example, consider this:

NSDateComponentsFormatter* dcf = [[NSDateComponentsFormatter alloc] init];
dcf.unitsStyle = NSDateComponentsFormatterUnitsStyleAbbreviated;

NSCalendar* cal = [NSCalendar calendarWithIdentifier: NSCalendarIdentifierGregorian];
cal.locale = [NSLocale localeWithLocaleIdentifier: @"es_ES"]; // Spanish locale for Spain

dcf.calendar = cal;

NSLog(@"%@", [dcf stringFromTimeInterval: 1000000]);

...which produces:

1 semana, 4 d, 13 h, 46 min, 40 s

So, this is a little different than your example format, but my guess is that somewhere deep in the ICU unicode standards documents, it is specified that if an interval has both weeks and seconds, that you get "semana" for weeks instead of "s". I'm not going to torture myself trying to find that document though.

So if you're looking for the ICU solution, this is it. If you're looking for something different, you may be stuck rolling your own. Also note that there are a few different "unit styles" so you might try others as well and pick the one that best fits your situation.

ipmcc
  • 29,581
  • 5
  • 84
  • 147