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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With