9

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

4

9 回答 9

35

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

Created by mattt who also created AFNetworking.

于 2012-04-09T16:01:15.770 回答
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 */
     }
}

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

于 2012-04-09T16:03:54.567 回答
6

我想要 Facebook 为他们的移动应用程序提供的日期格式,所以我创建了这个 NSDate 类别 - 希望它对某人有用(这种东西真的应该在标准库中!):)

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

于 2013-04-19T00:11:13.497 回答
4

如果这对您来说是个问题,还有 SEHumanizedTimeDiff 支持/即将支持多种语言:

https://github.com/sarperdag/SEHumanizedTimeDiff

于 2012-04-09T16:36:01.007 回答
3

There are about a million ways you could do this, but here's a quick one:

NSString* hoursAgo = [NSString stringWithFormat:@"%.0lf hours ago", fabs([date timeIntervalSinceNow] / 3600.0)]

Of course, this doesn't check that date is actually from the past, doesn't do anything but hours, etc. But, you probably get the idea.

timeIntervalSinceNow returns how many seconds have passed since a given date, with positive numbers being a date in the future and negative numbers being a date in the past. So, we get how many seconds have passed, divide it by 3600 seconds in an hour to compute the hours that have passed, and then put its absolute value into the string "n hours ago".

于 2012-04-09T16:03:12.833 回答
3

自从提出此问题以来,在较新版本的 iOS 中,NSDateFormatter已添加此功能。它现在可以使用该doesRelativeDateFormatting属性来完成。

于 2014-07-08T12:02:50.477 回答
3

这是一个很好的答案,从纪元(1970 年 1 月 1 日)开始,这将在几秒钟内完成,并返回一个格式良好的字符串,例如“3 分钟前”。只需使用您的日期对象调用它,如下所示:

[timeAgoFromUnixTime:[myDateObject timeIntervalSince1970]];

+ (NSString *)timeAgoFromUnixTime:(double)seconds
{
    double difference = [[NSDate date] timeIntervalSince1970] - seconds;
    NSMutableArray *periods = [NSMutableArray arrayWithObjects:@"second", @"minute", @"hour", @"day", @"week", @"month", @"year", @"decade", nil];
    NSArray *lengths = [NSArray arrayWithObjects:@60, @60, @24, @7, @4.35, @12, @10, nil];
    int j = 0;
    for(j=0; difference >= [[lengths objectAtIndex:j] doubleValue]; j++)
    {
        difference /= [[lengths objectAtIndex:j] doubleValue];
    }
    difference = roundl(difference);
    if(difference != 1)
    {
        [periods insertObject:[[periods objectAtIndex:j] stringByAppendingString:@"s"] atIndex:j];
    }
    return [NSString stringWithFormat:@"%li %@%@", (long)difference, [periods objectAtIndex:j], @" ago"];
}
于 2012-10-23T18:11:04.190 回答
2
+(NSString*)HourCalculation:(NSString*)PostDate

{
    NSLog(@"postdate=%@",PostDate);
    // PostDate=@"2014-04-02 01:31:04";
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [dateFormat setTimeZone:gmt];
    NSDate *ExpDate = [dateFormat dateFromString:PostDate];
    NSLog(@"expdate=%@",ExpDate);
    NSLog(@"expdate=%@",[NSDate date ]);
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [calendar components:(NSDayCalendarUnit|NSWeekCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:ExpDate toDate:[NSDate date] options:0];

//    NSLog(@"year=%d",components.year);
//    
//    NSLog(@"month=%d",components.month);
//    
//    NSLog(@"week=%d",components.week);
//    
//    NSLog(@"day=%d",components.day);
//    
//    NSLog(@"hour=%d",components.hour);
//    
//    NSLog(@"min=%d",components.minute);
//    
//    NSLog(@"sce=%d",components.second);
//    

    NSString *time;

    if(components.year!=0)   
    {
        if(components.year==1) 
        {
            time=[NSString stringWithFormat:@"%ld year",(long)components.year];  
        }
        else{
            time=[NSString stringWithFormat:@"%ld years",(long)components.year]; 
        }    
    }
    else if(components.month!=0) 
    {
        if(components.month==1)   
        {
            time=[NSString stringWithFormat:@"%ld month",(long)components.month]; 
        }
        else{
            time=[NSString stringWithFormat:@"%ld months",(long)components.month]; 
        }
      //  NSLog(@"%@",time);
    }
    else if(components.week!=0)
    {
        if(components.week==1)
        {
            time=[NSString stringWithFormat:@"%ld week",(long)components.week];
        }
        else{
            time=[NSString stringWithFormat:@"%ld weeks",(long)components.week];
        }
       // NSLog(@"%@",time);
    }
    else if(components.day!=0)
    {
        if(components.day==1)   
        {
            time=[NSString stringWithFormat:@"%ld day",(long)components.day];
        }
        else{
            time=[NSString stringWithFormat:@"%ld days",(long)components.day]; 
        } 
    }
    else if(components.hour!=0) 
    {
        if(components.hour==1)  
        {
            time=[NSString stringWithFormat:@"%ld hour",(long)components.hour];  
        }
        else{
            time=[NSString stringWithFormat:@"%ld hours",(long)components.hour];
        }
    }
    else if(components.minute!=0)  
    {
        if(components.minute==1)  
        {
            time=[NSString stringWithFormat:@"%ld min",(long)components.minute];
        }

        else{
            time=[NSString stringWithFormat:@"%ld mins",(long)components.minute]; 
        }
      //  NSLog(@"time=%@",time);
    }
    else if(components.second>=0){

       // NSLog(@"postdate=%@",PostDate);

       // NSLog(@"expdate=%@",[NSDate date ]);

        if(components.second==0)   
        {
            time=[NSString stringWithFormat:@"1 sec"];
        }
        else{
            time=[NSString stringWithFormat:@"%ld secs",(long)components.second];
        }
    }
    return [NSString stringWithFormat:@"%@ ago",time];

}

此代码将显示您的时间 ------------sec like 2 sec ag​​o ------------min like 2 mins ago --------- ---像 2 小时前的小时 ------------像 2 天前的天 ------------像 2 周前的周 -------- ----像 2 个月前一样的月 最后.... 像 2 年前一样的年 :) 试试这个

于 2014-11-25T10:14:24.847 回答
0

添加到解决方案尝试这种更简化的方法

    NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:passed toDate:[NSDate date] options:0];
    NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date];

    if (interval < 60) timestampString = [NSString stringWithFormat:@"%d seconds ago" ,today.second];
    else if (interval < 60 * 60) timestampString = [NSString stringWithFormat:@"%d minutes ago" ,today.minute];
    else if (interval < 60 * 60 * 24) timestampString = [NSString stringWithFormat:@"%d hours ago" ,today.hour];
    else timestampString = [NSString stringWithFormat:@"%d days ago" ,today.day];
于 2014-11-24T11:35:44.377 回答