iOS - Friendly NSDate format

2019-03-13 08:03发布

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.

9条回答
做自己的国王
2楼-- · 2019-03-13 08:31

There's also SEHumanizedTimeDiff which does/is about to support multiple languages if that's an issue for you:

https://github.com/sarperdag/SEHumanizedTimeDiff

查看更多
做个烂人
3楼-- · 2019-03-13 08:33

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".

查看更多
ゆ 、 Hurt°
4楼-- · 2019-03-13 08:35
+(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

查看更多
Bombasti
5楼-- · 2019-03-13 08:39

In newer versions of iOS since this question was asked, NSDateFormatter has had this ability added. It can now do it using the doesRelativeDateFormatting property.

查看更多
何必那么认真
6楼-- · 2019-03-13 08:42

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'. Simply call it with your date object like so:

[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"];
}
查看更多
【Aperson】
7楼-- · 2019-03-13 08:43

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

Created by mattt who also created AFNetworking.

查看更多
登录 后发表回答