iOS - 友好的NSDate格式 [英] iOS - Friendly NSDate format

查看:115
本文介绍了iOS - 友好的NSDate格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的应用程序中显示帖子的日期,现在我用这种格式进行:Fri,25 May。如何格式化NSDate以阅读2小时前的内容?使其更加用户友好。

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.

推荐答案

NSDateFormatter 不能像这样的东西;你将需要建立自己的规则。我猜这样的东西:

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 */
     }
}

所以这是打印x分钟前或x小时前从日期开始至24小时,通常是一天。

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.

这篇关于iOS - 友好的NSDate格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆