iOS - 友好的NSDate格式

8vi*_*ius 9 date date-format nsdate nsdateformatter ios

我需要向用户显示我的应用中的帖子日期,现在我以这种格式显示:"5月25日星期五".如何格式化NSDate以读取"2小时前"的内容?使其更加用户友好.

Lee*_*ong 35

看看FormaterKit https://github.com/mattt/FormatterKit

由mattt创建,他也创建了AFNetworking.


Tom*_*mmy 8

NSDateFormatter不能做那样的事情; 你需要建立自己的规则.我猜是这样的:

- (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 */
     }
}
Run Code Online (Sandbox Code Playgroud)

因此,打印时间为"x分钟前"或"x小时前"最多24小时,通常为一天.


N V*_*N V 6

我想像Facebook那样的日期格式用于他们的移动应用程序,所以我掀起了这个NSDate类别 - 希望它对某人有用(这种东西真的应该在标准库中!):)

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