ios - NSTimeInterval 到小时和分钟的错误转换

标签 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)。

知道为什么会这样吗?

谢谢!

最佳答案

没有理由为此使用 NSDateNSDateComponents

NSTimeInterval 是秒数。简单的数学运算可以给出小时、分钟和秒。

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

关于ios - NSTimeInterval 到小时和分钟的错误转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32569626/

相关文章:

ios - 旋转 UIView(再次)

ios - 如何将 subview 放在不同屏幕的正确位置

ios - 环球银行金融电信协会 : Convert String from XLM to NSDate

objective-c - CALayer - 未调用显示方法

ios - SWIFT:如何向 NSDate 对象添加小时数

iphone 如何从月份编号获取月份名称?

ios - 选项卡栏 Controller 根据登录隐藏选项卡 - 使用 Storyboard

iphone - ClLocationManager 委托(delegate)没有立即被调用?

ios - NSCalendar currentCalendar 不工作

iphone - 哪些类可以用作 NSDictionary 中的键?