iOS - Friendly NSDate format

前端 未结 9 2204
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 13:31

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

相关标签:
9条回答
  • 2021-02-04 14:08

    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!) :)

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

    0 讨论(0)
  • 2021-02-04 14:13

    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];
    
    0 讨论(0)
  • 2021-02-04 14:14

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

    0 讨论(0)
  • 2021-02-04 14:23

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

    https://github.com/sarperdag/SEHumanizedTimeDiff

    0 讨论(0)
  • 2021-02-04 14:23

    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"];
    }
    
    0 讨论(0)
  • 2021-02-04 14:24
    +(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

    0 讨论(0)
提交回复
热议问题