Search code examples
iphonensdateformatternsdatepicker

NSDateFormatter subtraction


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?


Solution

  • 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;