TimeIntervalSinceNow returns random numbers

timeIntervalstores returned random numbers. I would have thought that 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", timeInterval];
+3
source share
7 answers

% d for integers, use% f for double

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

Try this instead:

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

A few points in this snippet:

  • I used NSTimeIntervalinstead doublein the second line. They are equivalent because it is just a typedef, but for a clearer code.
  • , , [NSDate date] groceryItem.lastPurchased. , groceryItem.lastPurchased .
  • , groceryItem.lastPurchased . , , , . , . , groceryItem.lastPurchasedDate, .
+11

, . , date .

+7

timeIntervalSinceNow . , . , , .

, .

+6

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

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

, , NSTimeInterval, double.

+2

,

double timeInterval = - [date timeIntervalSinceNow];
+1

Source: https://habr.com/ru/post/1755012/


All Articles