Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format time intervals in Cocoa?

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:

  • Localization
  • Non-gregorian calendars.
like image 470
Georg Schölly Avatar asked Oct 02 '09 09:10

Georg Schölly


1 Answers

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];
}
like image 80
Dejal Avatar answered Nov 06 '22 05:11

Dejal