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;