我正在构建一个应用程序,而其中一部分逻辑是对大量 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)。
知道为什么会这样吗?
谢谢!
最佳答案
没有理由为此使用 NSDate
或 NSDateComponents
。
NSTimeInterval
是秒数。简单的数学运算可以给出小时、分钟和秒。
NSInteger hours = totalInterval / 3600;
NSInteger minutes = totalInterval / 60 % 60;
NSInteger seconds = totalInterval % 60;
关于ios - NSTimeInterval 到小时和分钟的错误转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32569626/