如何在Objective-C中正确格式化此日期?

时间:2011-08-31 19:14:22

标签: iphone objective-c cocoa nsdate nstimeinterval

我有以下字符串:

“2011-08-31 14:12:24”

我如何格式化它,以便显示为“2h ago”,如果这已经过了多长时间?

我有一些类似的代码,但不完全:

+(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;
}

2 个答案:

答案 0 :(得分:1)

结帐NSDateComponents。这是做这样的事情的好工具。 Date and Time Programming Guide可以引导您完成您想要完成的任务。

答案 1 :(得分:1)

我建立了一个NSValueTransformer来做到这一点。您可以查看它以获取您自己的代码的提示。 https://github.com/billgarrison/SORelativeDateTransformer