Sheehan Alam
Sheehan Alam

Reputation: 60889

How can I format this date properly in Objective-C?

I have the following string:

"2011-08-31 14:12:24"

How can I format it so that it displays as "2h ago" if that is how much time has elapsed?

I have some code that works similarly, but not quite:

+(NSString*)toShortTimeIntervalString:(NSString*)sDate  
{ 
    NSDateFormatter* df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSDate* date = [df dateFromString:[sDate stringByReplacingOccurrencesOfString:@"Z" withString:@"-0000"]];
    [df release];

    NSDate* today = [[NSDate alloc] init];
    NSDate *d = date; //[_twitter_dateFormatter dateFromString:sDate];
    NSTimeInterval interval = [today timeIntervalSinceDate:d];
    [today release];

    //TODO: added ABS wrapper
    double res = 0;
    NSString* result;
    if(interval > SECONDS_IN_WEEK)
    {
        res = fabs(interval / SECONDS_IN_WEEK);
        result = [NSString stringWithFormat:@"%1.0fw ago", res];
    }
    else if(interval > SECONDS_IN_DAY)
    {
        res = fabs(interval / SECONDS_IN_DAY);
        result = [NSString stringWithFormat:@"%1.0fd ago", res];
    }
    else if (interval > SECONDS_IN_HOUR){
        res = fabs(interval / SECONDS_IN_HOUR);
        result = [NSString stringWithFormat:@"%1.0fh ago", res];
    }
    else if (interval > SECONDS_IN_MIN) {
        res = fabs(interval / SECONDS_IN_MIN);
        result = [NSString stringWithFormat:@"%1.0fm ago", res];
    }
    else
    {
        interval = fabs(interval);
        result = [NSString stringWithFormat:@"%1.0fs ago", interval];
    }
    return result;
}

Upvotes: 0

Views: 256

Answers (2)

Bill Garrison
Bill Garrison

Reputation: 2049

I built an NSValueTransformer to do this. You can check it out for hints for your own code. https://github.com/billgarrison/SORelativeDateTransformer

Upvotes: 1

Christopher A
Christopher A

Reputation: 2961

Check out NSDateComponents. It is a great tool for doing stuff like this. The Date and Time Programming Guide can walk you through what you are trying to accomplish.

Upvotes: 1

Related Questions