iOS - Friendly NSDate format

前端 未结 9 2205
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 13:31

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\"

相关标签:
9条回答
  • 2021-02-04 14:25

    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.

    0 讨论(0)
  • 2021-02-04 14:28

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

    Created by mattt who also created AFNetworking.

    0 讨论(0)
  • 2021-02-04 14:31

    In newer versions of iOS since this question was asked, NSDateFormatter has had this ability added. It can now do it using the doesRelativeDateFormatting property.

    0 讨论(0)
提交回复
热议问题