views:

142

answers:

5

timeInterval keeps returning random numbers. Some positive. I would think the interval would continue increase with each call, but sometimes I get negative numbers or positive numbers.

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

If the receiver is earlier than the current date and time, the return value is negative. so if date is before now it will be negative.

Jesse Naugher
+1  A: 

This code [NSString stringWithFormat:@"%d", timeInterval]; is wrong. It is a DOUBLE. don't use %d. Use %f instead.

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

%d is for integers, use %f for double

[NSString stringWithFormat:@"%f", timeInterval];
willcodejavaforfood
+2  A: 

Try this instead:

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

A few points on this snippet:

  1. I've used NSTimeInterval instead of double in the second line. They are equivalent because it's just a typedef but it makes for clearer code.
  2. Rather than getting the time interval from a date in the past, I'm calculating the date and time right now with [NSDate date] and getting the time interval from groceryItem.lastPurchased. This will return a postive number as long as groceryItem.lastPurchased is in the past.
  3. I've edited my original code to pass groceryItem.lastPurchased to the time interval calculation directly. It isn't always a good idea to declare a variable for an item that is going to be used only once, especially in non-garbage-collected environments. Although declaring variables might make the code more readable there are other ways of improving readability. For example, in this case change the property to groceryItem.lastPurchasedDate which makes it a lot clearer.
Abizern
+1  A: 

It has been answered correctly above, I'd also add you should use the NSTimeInterval type rather than double as well.

ZaBlanc