【发布时间】:2011-09-04 18:25:53
【问题描述】:
我有以下数据:
----
ORIGINAL TIME 2011-09-04 12:04:36
FORMATTED TIME 2011-09-04T12:04:36-0700
RELATIVE TIME: 2517s ago
----
ORIGINAL TIME 2011-09-04 11:40:17
FORMATTED TIME 2011-09-04T11:40:17-0700
RELATIVE TIME: 1058s ago
----
ORIGINAL TIME 2011-09-04 08:05:00
FORMATTED TIME 2011-09-04T08:05:00-0700
RELATIVE TIME: 3h ago
----
ORIGINAL TIME 2011-09-04 07:16:00
FORMATTED TIME 2011-09-04T07:16:00-0700
RELATIVE TIME: 4h 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;
}
为什么我得到2517s ago 而它真的不应该输出为秒。应该是41m ago
本例中的间隔为-2517.0
【问题讨论】:
-
你如何定义
SECONDS_IN_MIN等? -
你做了什么来尝试自己调试这个?
-
@omz
#define SECONDS_IN_MIN 60 -
我认为你没有向我们展示什么。此外,如果您设置断点并使用调试器单步执行它,您应该能够在短时间内找出它。
标签: iphone objective-c cocoa-touch nsdate nsdateformatter