iOS - Friendly NSDate format

前端 未结 9 2208
伪装坚强ぢ
伪装坚强ぢ 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: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"];
    }
    

提交回复
热议问题