[Objective-C] – Human readable date diff

Sometimes you have to express date differences in a human readable way: “2 hours ago”, “yesterday”, etc. How to do this in Objective-C?

Here’s a nice solution

    - (NSString *) dateToName:(NSDate*)dt withSec:(BOOL)sec {
 
        NSLocale *locale = [NSLocale currentLocale];
        NSTimeInterval tI = [[NSDate date] timeIntervalSinceDate:dt];
        if (tI < 60) {
          if (sec == NO) {
               return NSLocalizedString(@"just now", @"");
           }
           return [NSString stringWithFormat:
                     NSLocalizedString(@"%d seconds ago", @""),(int)tI];
         }
         if (tI < 3600) {
           return [NSString stringWithFormat:
                     NSLocalizedString(@"%d minutes ago", @""),(int)(tI/60)];
         }
         if (tI < 86400) {
          return [NSString stringWithFormat:
                     NSLocalizedString(@"%d hours ago", @""),(int)tI/3600];
         }
 
         NSDateFormatter *relativeDateFormatter = [[NSDateFormatter alloc] init];
         [relativeDateFormatter setTimeStyle:NSDateFormatterNoStyle];
         [relativeDateFormatter setDateStyle:NSDateFormatterMediumStyle];
         [relativeDateFormatter setDoesRelativeDateFormatting:YES];
         [relativeDateFormatter setLocale:locale];
 
         NSString * relativeFormattedString = 
                [relativeDateFormatter stringForObjectValue:dt];
         return relativeFormattedString;
    }

Comments on this entry are closed.

  • Don’t forget to put the expression on singular when the the value is equal to one.

    It’s very ugly to write (or worst, to read) “1 minutes ago” or “1 days ago”, etc.

  • Chris

    Very helpful, thanks. Was wishing this was built into the date functions so was searching for a solution and yours works really well.