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



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

我遇到的问题是,当比较时间时,只返回具有开始日期的第一个对象的值。如果我用开始日期添加另一个值,时间设置为0,并在我想要将它们加在一起时重新开始。

如果您需要更多的信息,请告诉我

我使用for(object *obj in Array)之前,但它似乎有更多的问题

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,但这仍然不能解决time += timerint不工作的问题,这个数字重置每次我添加一个新对象,它也只返回最后添加的对象的值

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

此外,因为你每秒钟触发一个计时器,所以第二秒(0-59)很有可能是相同的。要检查这一点,在if(tTime.sDate)后面添加日志记录:

NSLog(@"tTime.sDate: %@", tTime.sDate);

,看看日期是否真的相同,只是秒数相同。

而不是:

NSDateComponents *component = [cal components:NSSecondCalendarUnit fromDate:tTime.sDate toDate:date options:0];
int tmpTime = [component second];
time = time + tmpTime;

试试这个:

NSTimeInterval tmpTime = -[tTime.sDate timeIntervalSinceDate:date];
time += tmpTime;

最新更新