0

I am reading a book about Objective-C and I am working on an exercise to add a category to the NSDate class called elapsedDays that returns the number of elapsed days between tow dates. Here is my try:

-(unsigned long) elapsedDays: (NSDate *) theDate{

return ([self timeIntervalSinceDate:theDate]/3600)/24;

}

Here is the main section of the program where I am testing my code:

NSDate *now = [NSDate date];

NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-(3600*24)];


NSLog(@"%@",now);
NSLog(@"%@",yesterday);

NSLog(@"%lu",([now elapsedDays:yesterday]));

The problem is that I am keep getting zero for the result:

2012-09-22 19:28:24 +0000
2012-09-21 19:28:24 +0000
0

I figured out that the division of [self timeIntervalSinceDate:theDate]/3600 is giving 23.99972222222222. and that's strange because it should give us 24 since the difference between the two dates is just one day which is 24 hours. I want to understand why this code is giving me a wrong numbers of seconds between the two dates.

I corrected that with rounding the result of the division but still want understand what's wrong.

return round ([self timeIntervalSinceDate:theDate] / 3600) / 24;  
MikkoP
  • 4,864
  • 16
  • 58
  • 106
Aladin
  • 53
  • 1
  • 5

3 Answers3

1

NSDate *now = [NSDate date];

NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-(3600*24)];

Above two statements will be executed one after the other. Because of this, you are getting 1 sec difference in 24 hours.

athspk
  • 6,722
  • 7
  • 37
  • 51
  • but as you can see in the output , it shows : 2012-09-22 19:28:24 +0000 2012-09-21 19:28:24 +0000 – Aladin Sep 23 '12 at 11:06
0

Don't do your own date calculations; let NSCalendar do them for you. See -components:fromDate:toDate:options: among other useful methods.

It's also helpful to learn the inherent limitations of floating-point arithmetic. For example, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Jon Reid
  • 20,545
  • 2
  • 64
  • 95
0

I think Yashavant's answer is probably correct. The strings that are logged may appear to be equal, but the underlying date objects might be off by milliseconds. Try doing this for yesterday, and see if it fixes your problem:

NSDate *yesterday = [NSDate dateWithTimeInterval:-86400 sinceDate:now];