2010-07-16 45 views
3

timeInterval不断返回随机数。我认为每次通话时间间隔都会继续增加,但有时我会得到负数,有时候会得到正数。timeIntervalSinceNow返回随机数

NSDate *date = groceryItem.lastPurchased; 
double timeInterval = [date timeIntervalSinceNow]; 
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", timeInterval]; 

回答

11

%d是整数,使用双

[NSString stringWithFormat:@"%f", timeInterval]; 
7

如果接收者早于当前日期和时间,则返回值为负值。所以如果date之前现在它将是负面的。

3

此代码[NSString stringWithFormat:@"%d", timeInterval];是错误的。这是一个DOUBLE。不要使用%d。改为使用%f。

[NSString stringWithFormat:@"%f", timeInterval]; 
11

%F试试这个:在这个片段中

NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:groceryItem.lastPurchased]; 
cell.detailTextLabel.text = [NSString stringWithFormat:@"%f", timeInterval]; 

的几点:

  1. 我在第二次使用NSTimeInterval而不是double东北。它们是等价的,因为它只是一个typedef,但它使代码更清晰。
  2. 我不是从过去的某个日期获取时间间隔,而是使用[NSDate date]来计算日期和时间,并从groceryItem.lastPurchased获取时间间隔。只要groceryItem.lastPurchased在过去,这将返回一个正数。
  3. 我编辑了我的原始代码,将groceryItem.lastPurchased直接传递给时间间隔计算。为一个只能使用一次的项目声明一个变量并不总是一个好主意,特别是在非垃圾收集环境中。虽然声明变量可能会使代码更具可读性,但还有其他提高可读性的方法。例如,在这种情况下,请将该属性更改为groceryItem.lastPurchasedDate,这使其更清晰。
2

它已被正确地回答上面,我还补充说你应该使用NSTimeInterval类型而不是双倍。

6

timeIntervalSinceNow将返回接收者与当前日期和时间之间的间隔。如果接收者早于当前日期和时间,则返回值为负值。如果接收者晚于当前日期和时间,则返回值为正数。

希望这会有所帮助。

1

您应该使用负号如下

double timeInterval = - [date timeIntervalSinceNow];