计算2个NSDates之间的时间(以秒为单位)

时间:2015-11-11 15:54:09

标签: objective-c nsdate

我无法计算“旧”和“现在”NSDate的输出。这是代码:

NSLog(@"past is %@", past);
NSDate *now = [NSDate date];

NSLog(@"Now time is is %@", now);

NSTimeInterval distanceBetweenDates = [now timeIntervalSinceDate:past];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;

NSLog(@" Time between is %i", hoursBetweenDates);

这是控制台输出:

2015-11-11 18:52:35.608 TaskTimer[2578:130664] past is 2015-11-11 15:52:02 +0000
2015-11-11 18:52:35.608 TaskTimer[2578:130664] now is 2015-11-11 15:52:35 +0000
2015-11-11 18:52:35.609 TaskTimer[2578:130664]  Time between is 0

我想补充一点,即使两个值之间的时间超过几分钟,最后一个值也是0。为什么是0?

2 个答案:

答案 0 :(得分:2)

因为您正在转换为整数并且向下舍入。什么<一个特定的整数值将向下舍入。几分钟就是< 1所以你会得到0小时。

如果你想要舍入到最近然后使用round(distanceBetweenDates / secondsInAnHour),或者为了向上舍入,你会使用ceil(distanceBetweenDates / secondsInAnHour)(尽管它也会在2.1到3之间)

答案 1 :(得分:1)

你的两个日期之间有33分钟,这只是一小时的一小部分。

NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;

该语句正在丢失小数精度,并向下舍入为0,这就是您正在显示的内容。

另一种方法是使用NSDateComponentsFormatter

以hh:mm:ss格式显示
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute |
    NSCalendarUnitSecond;

NSLog(@"Time between is %@", [formatter stringFromTimeInterval:distanceBetweenDates]);