开发者

timeIntervalSinceNow returning random numbers

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

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


%d is for integers, use %f for double

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


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.


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.


timeIntervalSinceNow will return the interval between the receiver and the current date and time. If the receiver is earlier than the current date and time, the return value is negative. If the receiver is later than the current date and time, the return value is positive.

Hope this helps.


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

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


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


You should use a negative sign as below

double timeInterval = - [date timeIntervalSinceNow];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜