Convert NSTimeInterval to a string in the format "1w 3d 4h 15m 21s", is it more convenient for the locale?

I want to convert NSTimeInterval to a format like

1w 3d 4h 15m 21s

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

+7
objective-c cocoa localization
source share
1 answer

NSDateComponentsFormatter is what you want. It may not create exactly what you are looking for, but my impression is that it aims to produce products that comply with standard ICU agreements. For example, consider the following:

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 from the format of your example, but I assume somewhere deep in the Unicode ICU standards documents it says that if the interval is weeks and seconds, then you get a "semann" for several weeks instead of "s". I am not going to torture myself trying to find this document.

So, if you are looking for an ICU solution, this is it. If you are looking for something else, you can freeze yourself. Also note that there are several different โ€œunit stylesโ€ so that you can try others and choose the one that best suits your situation.

+11
source share

All Articles