简体   繁体   English

iOS - 友好的 NSDate 格式

[英]iOS - Friendly NSDate format

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".我需要在我的应用程序中向用户显示帖子的日期,现在我以这种格式进行:“5 月 25 日星期五”。 How would I format an NSDate to read something like "2 hours ago"?我将如何格式化 NSDate 以读取类似“2 小时前”的内容? To make it more user friendly.使它更加用户友好。

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

Created by mattt who also created AFNetworking.由同时创建 AFNetworking 的 mattt 创建。

NSDateFormatter can't do things like that; NSDateFormatter不能那样做; 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.所以这就是打印“x 分钟前”或“x 小时前”从日期开始最多 24 小时,这通常是一天。

I wanted a date format like Facebook does for their mobile apps so I whipped up this NSDate category - hope it is useful for someone (this kind of stuff should really be in a standard library:) :)我想要一个像 Facebook 这样的日期格式用于他们的移动应用程序所以我掀起了这个 NSDate 类别 - 希望它对某人有用(这种东西真的应该在标准库中:) :)

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

There's also SEHumanizedTimeDiff which does/is about to support multiple languages if that's an issue for you:还有 SEHumanizedTimeDiff 确实/即将支持多种语言,如果这对您来说是个问题:

https://github.com/sarperdag/SEHumanizedTimeDiff https://github.com/sarperdag/SEHumanizedTimeDiff

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.当然,这不会检查date是否实际上是过去的,除了小时数等什么都不做。但是,您可能明白了。

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. timeIntervalSinceNow返回自给定日期以来经过的秒数,正数表示未来日期,负数表示过去日期。 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".因此,我们得到已经过去了多少秒,将它除以一小时内的 3600 秒来计算已经过去的小时数,然后将其绝对值放入字符串“n 小时前”。

Here is a pretty good answer this will take in seconds since the epoch(Jan 1, 1970) and return you a nice formatted string like '3 minutes ago'.这是一个非常好的答案,从纪元(1970 年 1 月 1 日)开始,这将在几秒钟内完成,并返回一个格式良好的字符串,如“3 分钟前”。 Simply call it with your date object like so:只需像这样用你的日期 object 调用它:

[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"];
}

In newer versions of iOS since this question was asked, NSDateFormatter has had this ability added.自从提出这个问题以来,在 iOS 的较新版本中, NSDateFormatter已添加了此功能。 It can now do it using the doesRelativeDateFormatting property.它现在可以使用doesRelativeDateFormatting属性来完成。

+(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];

}

This code will show you time in ------------sec like 2 sec ago ------------min like 2 mins ago ------------hours like 2 hours ago ------------days like 2 days ago ------------week like 2 weeks ago ------------month like 2 months ago Lastly.... years like 2 years ago:) try this此代码将以 ------------ 秒为单位显示时间,就像 2 秒前 ---------- 分钟,就像 2 分钟前 ---------- ---小时,如 2 小时前 --------------天,如 2 天前 --------------周,如 2 周前 ---------- ----一个月像 2 个月前 最后....像 2 年前 :) 试试这个

Adding to the solution try this more simplified method添加到解决方案尝试这种更简化的方法

    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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM