Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSTimeInterval to string in "1w 3d 4h 15m 21s" format, locale-friendly?

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?

like image 548
tenfour Avatar asked Jan 29 '15 16:01

tenfour


1 Answers

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.

like image 164
ipmcc Avatar answered Oct 17 '22 12:10

ipmcc