Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Friendly NSDate format

I need to display the date of posts in my app to the user, right now I do it in this format: "Fri, 25 May". How would I format an NSDate to read something like "2 hours ago"? To make it more user friendly.

like image 279
8vius Avatar asked Apr 09 '12 15:04

8vius


3 Answers

Take a look at FormaterKit https://github.com/mattt/FormatterKit

Created by mattt who also created AFNetworking.

like image 74
Lee Armstrong Avatar answered Oct 29 '22 01:10

Lee Armstrong


NSDateFormatter can't do things like that; you're going to need to establish your own rules. I guess something like:

- (NSString *)formattedDate:(NSDate *)date
{
     NSTimeInterval timeSinceDate = [[NSDate date] timeIntervalSinceDate:date];

     // print up to 24 hours as a relative offset
     if(timeSinceDate < 24.0 * 60.0 * 60.0)
     {
         NSUInteger hoursSinceDate = (NSUInteger)(timeSinceDate / (60.0 * 60.0));

         switch(hoursSinceDate)
         {
              default: return [NSString stringWithFormat:@"%d hours ago", hoursSinceDate];
              case 1: return @"1 hour ago";
              case 0:
                  NSUInteger minutesSinceDate = (NSUInteger)(timeSinceDate / 60.0);
                  /* etc, etc */
              break;
         }
     }
     else
     {
          /* normal NSDateFormatter stuff here */
     }
}

So that's to print 'x minutes ago' or 'x hours ago' up to 24 hours from the date, which will usually be one day.

like image 20
Tommy Avatar answered Oct 29 '22 03:10

Tommy


I wanted a date format like Facebook does for their mobile apps so I whipped up this NSDate category - hope it is useful for someone (this kind of stuff should really be in a standard library!) :)

https://github.com/nikilster/NSDate-Time-Ago

like image 37
N V Avatar answered Oct 29 '22 03:10

N V