Objective-C 中计算相对时间的问题

发布于 2024-12-02 22:09:48 字数 2000 浏览 1 评论 0原文

我有以下数据:

 ----
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 前

本例中的间隔是 -2517.0

I have the following data:

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

I have some code to calculate the relative time (I am passing in the formatted time):

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

Why am I getting 2517s ago when it should really not output that as seconds. It should be 41m ago

The interval in this case is -2517.0

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

狼性发作 2024-12-09 22:09:48

我建议使用 NSCalendar 的 - (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts 方法 要获取现在和您的日期之间的相对时间单位,请使用以下内容:

NSDate *dateToCompare = pointerToYourDatePulledFromTheStringRep;
NSInteger numberOfUnits;
NSString *unitString;
NSDateComponents *comps = [[NSCalendar currentCalendar] 
                          components:(NSWeekCalendarUnit | 
                                       NSDayCalendarUnit | 
                                      NSHourCalendarUnit | 
                                    NSMinuteCalendarUnit | 
                                    NSSecondCalendarUnit) 
                           fromDate:dateToCompare 
                             toDate:[NSDate date]
                            options:0];
if ([comps week] > 0) {
   numberOfUnits = [comps week];
   unitString = @"week";
} else if ([comps day] > 0) {
   numberOfUnits = [comps day];
   unitString = @"day";
} else if... // hour, minute, second

result = [NSString stringWithFormat:@"%d %@%@",
                                    numberOfUnits,
                                    unitString,
                                    (numberOfUnits != 1 ? @"s" : @"")]; 
                                    // last bit deals with plurality

这样,操作系统函数就会处理所有毛茸茸的日期数学,您将获得精确性和多日历兼容性的好处。

至于你的问题(技术上)关于为什么你的秒数不是分钟,我猜 SECONDS_IN_MIN 定义不正确。但是,再次使用 NSCalendar 可以为您提供更可靠的答案。

I'd recommend using the - (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts method of NSCalendar to get the relative time units between now and your dates, using something like this:

NSDate *dateToCompare = pointerToYourDatePulledFromTheStringRep;
NSInteger numberOfUnits;
NSString *unitString;
NSDateComponents *comps = [[NSCalendar currentCalendar] 
                          components:(NSWeekCalendarUnit | 
                                       NSDayCalendarUnit | 
                                      NSHourCalendarUnit | 
                                    NSMinuteCalendarUnit | 
                                    NSSecondCalendarUnit) 
                           fromDate:dateToCompare 
                             toDate:[NSDate date]
                            options:0];
if ([comps week] > 0) {
   numberOfUnits = [comps week];
   unitString = @"week";
} else if ([comps day] > 0) {
   numberOfUnits = [comps day];
   unitString = @"day";
} else if... // hour, minute, second

result = [NSString stringWithFormat:@"%d %@%@",
                                    numberOfUnits,
                                    unitString,
                                    (numberOfUnits != 1 ? @"s" : @"")]; 
                                    // last bit deals with plurality

This way, the OS functions deal w/ all the hairy date math, and you reap the benefits of exactness and multi-calendar compatibility.

As to your your question (technically) about why your seconds are coming out NOT as minutes, I'd guess that SECONDS_IN_MIN is defined incorrectly. But, again, using NSCalendar gives you a more robust answer.

梦罢 2024-12-09 22:09:48

顺便说一句,如果 interval-2517.0,您应该检查 (interval <-60)。如果您的所有时间都是过去的,则所有宏都应该定义为负数,并且您的比较应该是 <,而不是 >。考虑到这一点,不确定您的小时时间是如何格式化的...

如果您的时间可以,您可能需要在所有比较中执行 (fabs(interval) > SECONDS_IN_UNIT) (并将它们定义为正值)是在未来或过去。

BTW-- if interval is -2517.0, you should be checking for (interval < -60). If all your times are in the past, all your macros should be defined negative and your comparisons should be <, not >. Not sure how your hour times formatted that way, considering this...

You may want to do (fabs(interval) > SECONDS_IN_UNIT) (and define them positive) in all your comparisons if your times can be in the future or the past.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文