I have a datepicker for the field "From" and "To" and I want the result of the subtraction. for example: toValue-fromValue and the result would be in hours. How to do that?
Asked
Active
Viewed 228 times
2 Answers
2
The difference of the two NSdate
objects can be calculated using timeIntervalSinceDate
:
NSTimeInterval diff = [toDate timeIntervalSinceDate:fromDate];
The result is given in seconds. Then, you calculate the hours like this:
NSInteger hours = diff / 3600;

albertamg
- 28,492
- 6
- 64
- 71
-
1It should be noted that NSTimeInterval is an alias for "double" -- a double-precision float. – Hot Licks Jul 08 '11 at 20:58
-
I am getting EXC_BAD_ACCESS. I tried with double diff=... but its not working either. – BlackM Jul 09 '11 at 08:33
-
@user776720 I think you have a memory management problem with your `NSDate` objects. Can you post the code? – albertamg Jul 09 '11 at 09:41
-
Fixed. I didnt retaining the toDate and fromDate. – BlackM Jul 09 '11 at 12:49
1
If you have two NSDate objects you can compare them using the timeIntervalSinceDate
method
NSDate* fromDate = //Get from date picker
NSDate* toDate = //Get from date picker
NSTimeInterval = [fromDate timeIntervalSinceDate:toDate];
NSInteger hours = timeInterval / 60*60; //60 seconds per minute, 60 minutes per hour

DHamrick
- 8,338
- 9
- 45
- 62