【发布时间】:2015-09-14 16:32:42
【问题描述】:
我正在构建一个应用程序,而部分逻辑是总结大量 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)。
知道为什么会这样吗?
谢谢!
【问题讨论】:
标签: ios objective-c nsdate nsdatecomponents