首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在NSMutableArray NSDateComponent中比较多个日期之间的时间仅返回第一个日期的值

在NSMutableArray NSDateComponent中比较多个日期之间的时间仅返回第一个日期的值
EN

Stack Overflow用户
提问于 2014-06-01 01:54:52
回答 1查看 225关注 0票数 0

基本上,我有一个可以包含多个NSManagedObjects的数组,我正在尝试对这些对象进行排序,对于那些有开始日期的对象,我想要比较开始日期和现在之间的时间,或者开始日期和结束日期之间的时间(如果设置了)。最后,设置一个计时器,以便在一秒钟内刷新此信息。

我遇到的问题是,当比较时间时,只返回第一个对象的值和开始日期。如果我将另一个值与开始日期相加,则时间设置为0,并在我希望将它们相加时重新开始。

如果您需要更多信息,请让我知道

我以前使用过for(数组中的对象*obj ),但是它似乎有更多的问题

代码语言:javascript
复制
int time = 0;
if([_ttimes count] != 0){

    for(int i=0; i < [_ttimes count]; ++i){
        TTime *tTime = [_ttimes objectAtIndex:i];
        NSLog(@"time%i", i);
        if(tTime.sDate){
            NSCalendar *cal = [NSCalendar currentCalendar];
            NSDate *date = [NSDate date];
            if(tTime.eDate){
                date = tTime.eDate;
            }
            NSDateComponents *component = [cal components:NSSecondCalendarUnit fromDate:tTime.sDate toDate:date options:0];
            int tmpTime = [component second];
            time = time + tmpTime;
        }
    }
    _ticketTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TotalWorkTime) userInfo:nil repeats:NO];
}

将方法更改为:

-(void)TotalWorkTime{ double time = 0; if([_ttimes count] != 0){ for(TTime *tTime in _ttimes){ NSDate *date = [NSDate date]; if(tTime.eDate){ date = tTime.eDate; } NSTimeInterval timerint = -[tTime.sDate timeIntervalSinceDate:date]; time = time + timerint; } NSLog(@"Time:%f", time); } }

这似乎返回了一个更准确的时间,但是,谢谢你,Zaph,但这仍然没有解决问题,时间+=定时器不工作,这个数字重置每次我添加一个新的对象,它也只返回最后添加的对象的值。

EN

回答 1

Stack Overflow用户

发布于 2014-06-01 02:47:20

NSDateComponents components:NSSecondCalendarUnit的问题是它只返回0-59。(有罕见的例外)

此外,由于您每秒都会触发一个计时器,因此秒(0-59)很有可能是相同的。要检查这一点,在if(tTime.sDate)之后添加日志记录

代码语言:javascript
复制
NSLog(@"tTime.sDate: %@", tTime.sDate);

看看日期是否真的一样,只是秒是一样的。

而不是这样:

代码语言:javascript
复制
NSDateComponents *component = [cal components:NSSecondCalendarUnit fromDate:tTime.sDate toDate:date options:0];
int tmpTime = [component second];
time = time + tmpTime;

试试这个:

代码语言:javascript
复制
NSTimeInterval tmpTime = -[tTime.sDate timeIntervalSinceDate:date];
time += tmpTime;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23973402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档