8

I need a method to format a NSTimeInterval (time span in seconds) into a string to produce something like "about 10 minutes ago", "1h, 20min", or "less than 1 minute".

-(NSString*) formattedTimeSpan:(NSTimeInterval)interval;

Target platform is iOS. Sample code is welcome.

Felix
  • 35,354
  • 13
  • 96
  • 143

3 Answers3

30

This is a category for NSDate. It's not exactly using an NSTimeInterval, well internally :) I assume you are working with timestamps.

Header file NSDate+PrettyDate.h

@interface NSDate (PrettyDate)

- (NSString *)prettyDate;

@end

Implementation NSDate+PrettyDate.m

@implementation NSDate (PrettyDate)

- (NSString *)prettyDate
{
    NSString * prettyTimestamp;

    float delta = [self timeIntervalSinceNow] * -1;

    if (delta < 60) {
        prettyTimestamp = @"just now";
    } else if (delta < 120) {
        prettyTimestamp = @"one minute ago";
    } else if (delta < 3600) {
        prettyTimestamp = [NSString stringWithFormat:@"%d minutes ago", (int) floor(delta/60.0) ];
    } else if (delta < 7200) {
        prettyTimestamp = @"one hour ago";      
    } else if (delta < 86400) {
        prettyTimestamp = [NSString stringWithFormat:@"%d hours ago", (int) floor(delta/3600.0) ];
    } else if (delta < ( 86400 * 2 ) ) {
        prettyTimestamp = @"one day ago";       
    } else if (delta < ( 86400 * 7 ) ) {
        prettyTimestamp = [NSString stringWithFormat:@"%d days ago", (int) floor(delta/86400.0) ];
    } else {
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];

        prettyTimestamp = [NSString stringWithFormat:@"on %@", [formatter stringFromDate:self]];
        [formatter release];
    }

    return prettyTimestamp;
}
Nick Weaver
  • 47,228
  • 12
  • 98
  • 108
  • I believe I've seen that code somewhere in a twitter client. It is not exactly what I need, but I can work with it. I need more precision for the time, like 1h, 20min. – Felix Apr 21 '11 at 09:52
  • 2
    I've ported this from a javascript lib for a social network app. If you need more precision, you can easily add more interval blocks. Just meant as an idea. – Nick Weaver Apr 21 '11 at 10:01
  • ^Yeah, I recognize that from a JS lib I use on my social networking site! Pretty cool to see it laid out in Objective-C like this! – Jacob Pritchett Jun 19 '13 at 03:06
3

You might want to refer to Facebook three20 framework. In their NSDateAdditions, they provided a few pretty formats for date. It might be better than you extend it.

Refer to the source at https://github.com/facebook/three20/blob/master/src/Three20Core/Sources/NSDateAdditions.m

- (NSString*)formatShortRelativeTime; will give you "<1m", "50m", "3h", "3d"

samwize
  • 25,675
  • 15
  • 141
  • 186
1

Here is one that formats the date in the style of Facebook:

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

N V
  • 742
  • 1
  • 6
  • 21