I'm looking for a class that formats time intervals like this:
1 hour 3 minutes 2 hours 5 minutes 12 seconds 5 days 2 hours
Is there anything built-in or a library that supports this kind of time interval formatting?
I thought about doing it myself, but there are all sorts of problems:
An old question, but for anyone who stumbles on this, check out NSDateComponentsFormatter
.
For example, here's a NSDate
category method from my DejalFoundationCategories open source project:
+ (NSString *)dejal_relativeStringForTimeInterval:(NSTimeInterval)timeInterval style:(NSDateComponentsFormatterUnitsStyle)unitsStyle maximumUnits:(NSInteger)maximumUnits keepZero:(BOOL)keepZero defaultValue:(NSString *)defaultValue;
{
// If more than 10 years, assume distant past or future:
if (abs(timeInterval) > 60 * 60 * 24 * 365 * 10)
{
return defaultValue;
}
NSDateComponentsFormatter *formatter = [NSDateComponentsFormatter new];
formatter.unitsStyle = unitsStyle;
formatter.maximumUnitCount = maximumUnits;
if (keepZero)
{
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropLeading | NSDateComponentsFormatterZeroFormattingBehaviorDropMiddle;
}
else
{
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll;
}
return [formatter stringFromTimeInterval:timeInterval];
}
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