错误地将NSTimeInterval转换为小时和分钟

时间:2015-09-14 16:32:42

标签: ios objective-c nsdate nsdatecomponents

我正在构建一个应用程序,而逻辑的一部分是总结很多NSTimeIntervals并将结果转换为小时和分钟。

我使用for循环添加区间如此

NSTimeInterval totalInterval = 0;
for (MyObject *currentObject in _myList)
{
    totalInterval += [currentObject.endDate timeIntervalSinceDate:currentObject.startDate];
}

此函数将返回NSDateComponents类型的对象:

// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitDay | NSCalendarUnitMonth;

NSDate *startDate = [self dateByOmittingSeconds:[NSDate date]]; // get the current time
NSDate *endDate = [[NSDate alloc] initWithTimeInterval:totalInterval sinceDate:startDate];

return [[NSCalendar currentCalendar] components:unitFlags fromDate:startDate  toDate:endDate  options:0];

然后我将其格式化为更易读的类型(NSString)供用户阅读:

- (NSString *)timeFormatted:(NSDateComponents *)workhours
{
    return [NSString stringWithFormat:@"%ldh %ldm", (long)[workhours hour], (long)[workhours minute]];
}

但是timeFormatted函数的结果输出14h 11m,而totalInterval中的秒数是正确的(137460s)。

知道为什么会这样吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

没有理由使用NSDateNSDateComponents

NSTimeInterval是几秒钟。简单的数学运算可以为您提供小时,分钟和秒钟。

NSInteger hours = totalInterval / 3600;
NSInteger minutes = totalInterval / 60 % 60;
NSInteger seconds = totalInterval % 60;