我需要在我的应用程序中显示帖子的日期给用户,现在我用这种格式:“5月25日星期五”.如何格式化NSDate以阅读“2小时前”的内容?使其更加用户友好.
解决方法
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 */
}
}
所以这是打印’x分钟前’或’x小时前’从日期起24小时,通常是一天.