简体   繁体   English

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

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

I have the following string: 我有以下字符串:

"2011-08-31 14:12:24" “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? 我如何格式化它,以便显示为“2h ago”,如果这已经过了多长时间?

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

Check out NSDateComponents . 查看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. 日期和时间编程指南可以引导您完成您要完成的任务。

I built an NSValueTransformer to do this. 我建立了一个NSValueTransformer来做到这一点。 You can check it out for hints for your own code. 您可以查看它以获取您自己的代码的提示。 https://github.com/billgarrison/SORelativeDateTransformer https://github.com/billgarrison/SORelativeDateTransformer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM